10

When I try to check the existence of a particular file, I get java.lang.illegalArgumentException: File contains a path separator

What is the right way to do this using getFileStreamPath(..)?

File file = getActivity().getFileStreamPath("mnt/sdcard/photo/1342147146535.jpg");
   if(file.exists()){
     Toast.makeText(getActivity(), "File exists in /mnt", Toast.LENGTH_SHORT);
}

I also tried the following to replace the first line of the above codes. None of these worked.

File file = getActivity().getFileStreamPath("file:///mnt/sdcard/photo/aviary_1342147146535.jpg");
            File file = getActivity().getFileStreamPath("/mnt/sdcard/photo/1342147146535.jpg");
//          File file = getActivity().getFileStreamPath("mnt/sdcard/photo/1342147146535.jpg");
//          File file = getActivity().getFileStreamPath("file:///mnt/sdcard/photo/1342147146535.jpg");

            if(file.exists()){
            Toast.makeText(getActivity(), "File exists in /mnt", Toast.LENGTH_SHORT);}
            else {
                Toast.makeText(getActivity(), "File NOT exists in /mnt", Toast.LENGTH_SHORT);}
Nermeen
  • 15,883
  • 5
  • 59
  • 72
Jason O.
  • 3,168
  • 6
  • 33
  • 72
  • 1
    possible duplicate of [I can't make sense Context.getFileStreamPath trying to test wether a file path exists?](http://stackoverflow.com/questions/9270098/i-cant-make-sense-context-getfilestreampath-trying-to-test-wether-a-file-path-e) – Thorsten Dittmar Jul 13 '12 at 09:09
  • why not using `File file = new File("path");` and you are using file streaming? Despite that getFileStreamPath does not work that way as it is mentioned in the previous comment. – 10s Jul 13 '12 at 09:10
  • 1
    check this answer: http://stackoverflow.com/questions/5963535/java-lang-illegalargumentexception-contains-a-path-separator – Nermeen Jul 13 '12 at 09:10

2 Answers2

3

I had the same problem when I was trying with method getFileStreamPath. I think it takes file as parameter, not whole path; that's why it threw an exception. I solved with following method.

public static Boolean fileExist(Activity activity , String filePath) {
        String finalPath = activity.getFilesDir().toString() + File.separator + filePath;
        File file = new File(finalPath);
        return file.exists();
    }
LarsH
  • 27,481
  • 8
  • 94
  • 152
user1154390
  • 2,331
  • 3
  • 25
  • 32
0

write below code for that.

File file = getActivity().getFileStreamPath("/mnt/sdcard/photo/1342147146535.jpg");
if(file.exists()){
    Toast.makeText(getActivity(), "File exists in /mnt", Toast.LENGTH_SHORT);
}

And Follow below link for more detail.

File Path

Community
  • 1
  • 1
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
  • 4
    getFileStreamPath() cannot accept filenames with file separators. You get an illegal argument exception. – BeccaP Jul 21 '15 at 22:30