Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

android - 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 MSG as file exist. Why is it so??

String pdf;
String filenameWithExtension="";

protected void onCreate(Bundle savedInstanceState) {

        Intent intent=getIntent();
        pdf=intent.getStringExtra("pdfurl");
        String PATH2 = Environment.getExternalStorageDirectory()+"/pictures";
        Log.v("log_tag initial path", "PATH: " + PATH2);
        File file2 = new File(PATH2);
        if(file2.exists()==true)
        {
        }else
        {   
            Log.v("directory is created", "new  dir");
            file2.mkdir();
        }

        /**extracting the pdf filname from url**/
        int slashIndex = pdf.lastIndexOf('/');
        int dotIndex = pdf.lastIndexOf('.');
        filenameWithExtension=pdf.substring(slashIndex + 1);

        DownloadFile downloadFile = new DownloadFile(filenameWithExtension);
        downloadFile.execute(pdf);
}
private class DownloadFile extends AsyncTask<String, Integer, String>{

        String filename="";
        public DownloadFile(String _filename) {
            this.filename=_filename;

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

        @Override
        protected String doInBackground(String... str) {

            Log.v("name of file",this.filename);
            if(filecheck.exists()){
                Log.v("in if condition", "file is alredy exist");

            }else{
                Log.v("in else condition","file not present....");
                try {
                    URL url = new URL(str[0]);
                    HttpURLConnection c = (HttpURLConnection)url.openConnection();
                    c.setRequestMethod("GET");
                    c.setDoOutput(true);
                    c.connect();
                    // this will be useful so that you can show a typical 0-100% progress bar
                    int lenghtOfFile = c.getContentLength();

                    // downlod the file
                    // InputStream input = new BufferedInputStream(url.openStream());
                    //OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");
                    String PATH = Environment.getExternalStorageDirectory()+ "/pictures/";
                    Log.v("log_tag", "PATH: " + PATH);
                    File file = new File(PATH);
                    Boolean check=filecheck.createNewFile();
                    Log.v("check file creation..::", check.toString());
                    if(file.mkdirs()==false)
                    {   
                        Log.v("file is alredy exist in sdcard", "exist file");
                    }else
                    {   
                        Log.v("file is created in card", "new  dir");
                        file.mkdirs();
                    }

                    File outputFile = new File(file,filenameWithExtension);
                    FileOutputStream fos = new FileOutputStream(outputFile);

                    InputStream is = c.getInputStream();
                    long total = 0;

                    byte[] buffer = new byte[1024];
                    int len1 = 0;
                    while ((len1 = is.read(buffer)) != -1) {
                        total +=len1;

                         publishProgress((int)(total*100/lenghtOfFile));

                         fos.write(buffer, 0, len1);
                    }
                    fos.close();
                    is.close();
            } catch (IOException e) {
                Log.d("log_tag of background", "Error: " + e);
                }
            }
            Log.v("In aync task filename extension",filenameWithExtension);

            return filenameWithExtension;
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...