【问题标题】:How to check file exist or not and if not create a new file in sdcard in async task如何检查文件是否存在以及是否在异步任务中的 sdcard 中创建新文件
【发布时间】:2011-10-19 06:50:07
【问题描述】:

我想从服务器下载 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, 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;
        }

【问题讨论】:

  • 还有哪些条件执行没有完成?
  • 我已经这样做了,但问题是如果 doInBackground() 方法的条件,它总是会进来,因为我没有创建文件。
  • 如果你解决了那么好,否则看看我编辑的答案。
  • 还有一件事是一个好的调试器,然后你就不需要为这类错误寻求帮助。谢谢 :-) 调试愉快。

标签: android


【解决方案1】:

您可以使用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();

new File("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);

【讨论】:

  • 感谢您的回复。请检查上面的代码,我已经检查了代码 donloadfile 类,但它总是给我消息,因为文件存在但我没有创建。
  • +1 for,注意:exists() 会为目录返回 true,我忘了。
  • @PavanMore : 检查你的变量文件名是否为空。
  • 谢谢。我得到了答案,你是对的文件名是空的。
  • 关于上述建议的问题。如果我执行 File f = new File(filePathString); if(f.exists()) {....} 东西并且该文件以前不存在,我期待“新文件(...):会创建有问题的文件。我错过了什么?
猜你喜欢
  • 2013-10-05
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 2019-09-29
  • 2011-10-09
相关资源
最近更新 更多