Hayk Nahapetyan Hayk Nahapetyan - 9 months ago 56
Android Question

android file.exists does not work correctly

In my android application I have problem with

function. Below is my function that gets two variables.
is full path of file , and
is the path of directory in what I must copy the file. For example
from == "/mnt/sdcard/Media/Image/Abstact wallpapers/abstraction-360x640-0033.jpg";
to == "/mnt/sdcard";

public static boolean copyFile(String from, String to) {
File sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
int end = from.toString().lastIndexOf("/") - 1;
String str1 = from.toString().substring(0, end);
String str2 = from.toString().substring(end+2, from.length());
File source = new File(str1, str2);
File destination= new File(to, str2);
if (source.exists()) {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
return true;
} catch (Exception e) {
return false;

When I debug it ,
if (source.exists())
returns false but my file with this path exists. What I'm doing wrong?

Answer Source

The problem lies in the way you are creating the File source.

There is a bug in it that is generating a File with the wrong directory.

So when you call .exists it simply doesn't, as you are referring to the wrong file path

public String substring (int start, int end)

Since: API Level 1 Returns a string containing a subsequence of characters from this string. The returned string shares this string's backing array.

Parameters start the offset of the first character. end the offset one past the last character. Returns a new string containing the characters from start to end - 1

You have misused substring. It get the substring from start to end -1. You have -1 yourself, so infact you have actually caused it to -2 from the folder directory.

If you remove the extra -1 and decrease start of next substring by 1, it should work.

int end = from.toString().lastIndexOf("/") ;
String str1 = from.toString().substring(0, end);
String str2 = from.toString().substring(end+1, from.length());


An improved way would be to make use of the File methods

File source = new File(from); //creates file from full path name    
String fileName = source.getName(); // get file name
File destination= new File(to, fileName ); // create destination file with name and dir.