android – 如何检查文件是否存在,如果没有在异步任务的sdcard中创建新文件

前端之家收集整理的这篇文章主要介绍了android – 如何检查文件是否存在,如果没有在异步任务的sdcard中创建新文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从服务器下载pdf并存储在sdcard上.我尝试像下面的代码,但它不会进入其他条件,因为我没有创建一个文件,仍然会给MSG文件存在.为什么呢
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,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;
        }

解决方法

您可以使用 File.exists()检查文件是否存在
File f = new File(filePathString);
   if(f.exists())
   { 
     /* do something */ 
   }
   else
   {
      file.mkdirs();
      //And your other stuffs goes here
   }

注意:exists()将为目录返回true

如果你想检查一个特定的文件是否存在,你必须使用File.isFile()

boolean fileExists =  new File("path/to/file.txt").isFile();

文件(“C:/”).exists()将返回true,但不允许您作为文件打开和读取.

你的代码中的问题是你的文件名是空的.

编辑2:

尝试这个 :

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

public DownloadFile(String _filename) {
        this.filename=_filename;
        PATH = Environment.getExternalStorageDirectory()+"/pictures/"+filename;
        filecheck=new File(PATH);
   }

要么

或者在AsyncTask的onPreExecute()中放置这两个语句

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

猜你在找的Android相关文章