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

时间:2011-10-19 06:50:08

标签: android

我想从服务器下载pdf并存储在SD卡上。我尝试类似下面的代码,但它不会进入其他条件,因为我没有创建一个文件仍然会给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;
        }

1 个答案:

答案 0 :(得分:28)

您可以使用File.exists()

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

注意exists()也会为目录返回

如果要检查是否存在特定文件,则必须使用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);