How to check file exist or not and if not create a new file in sdcard in async task

前端 未结 1 1328
無奈伤痛
無奈伤痛 2020-12-14 04:13

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 gi

1条回答
  •  天涯浪人
    2020-12-14 04:41

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

       File f = new File(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()

    boolean fileExists =  new File("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="";
    String PATH=""; 
    File fileCheck=null;
    
    public DownloadFile(String _filename) {
            this.filename=_filename;
            PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;
            filecheck=new File(PATH);
       }
    

    Or

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

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

    0 讨论(0)
提交回复
热议问题