Skip to content Skip to sidebar Skip to footer

How To Check File Exist Or Not And If Not Create A New File In Sdcard In Async Task

I want to download pdf from server and store on sdcard. I try something like following code but it will not go in else condition, as I am not created a file still it will giving MS

Solution 1:

You can check whether File exists or not by using File.exists()

Filef=newFile(filePathString);
   if(f.exists())
   { 
     /* do something */ 
   }
   else
   {
      file.mkdirs();
      //And your other stuffs goes here
   }

Note : exists() will return true for directories, too

If you want to check for a particular file that exists or not you have to use File.isFile()

booleanfileExists=newFile("path/to/file.txt").isFile();

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

The problem in your code is your filename is null.

Edit 2 :

Try this :

String filename="";
StringPATH=""; 
File fileCheck=null;

publicDownloadFile(String _filename) {
        this.filename=_filename;
        PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;
        filecheck=newFile(PATH);
   }

Or

or in onPreExecute() of AsyncTask you put this two statements

PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;filecheck=new File(PATH);

Post a Comment for "How To Check File Exist Or Not And If Not Create A New File In Sdcard In Async Task"