android - 如何检查文件是否存在,如果不存在则在异步任务中的 sdcard 中创建一个新文件

标签 android

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

最佳答案

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

关于android - 如何检查文件是否存在,如果不存在则在异步任务中的 sdcard 中创建一个新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7817551/

相关文章:

java - 回调怪异行为(Android、Picasso 库)

android - 验证 Android 等智能手机应用程序的不同方法

javascript - 使用 JavaScript 在 Android 4.0+ WebView 中检测键盘事件

android - 来自 XML 资源的字符串引用

android - iPad、androidPad 和 Windows 8/HTML 的单一来源?

java - Android Firebase 时间戳

android - jackson 在反序列化期间更改日期

android - 如何在 Android 应用程序中使用不支持的语言?

android - 如果指定了 COLLECTION_SOCIAL,Google Play 服务问题 loadPlayerCenteredScores 方法不会返回圆圈分数

c# - android从设备上传位图到c#服务器