2011-10-19 27 views
11

Tôi muốn tải xuống pdf từ máy chủ và lưu trữ trên sdcard. Tôi thử một cái gì đó giống như mã sau nhưng nó sẽ không đi trong điều kiện khác, như tôi không tạo ra một tập tin vẫn còn nó sẽ cho MSG như tập tin tồn tại. Tại sao nó như vậy??Cách kiểm tra tệp tồn tại hay không và nếu không tạo tệp mới trong sdcard trong tác vụ async

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; 
     } 
+0

Trong đó điều kiện khác thực hiện không được thực hiện? – user370305

+0

Tôi đã làm điều đó, nhưng vấn đề là nó sẽ luôn luôn đi vào bên trong nếu điều kiện của phương thức doInBackground() vì tôi không tạo ra tệp. –

+0

Nếu bạn giải quyết thì tốt, chỉ cần nhìn vào câu trả lời đã chỉnh sửa của tôi. – user370305

Trả lời

27

Bạn có thể kiểm tra xem tập tin tồn tại hay không bằng cách sử dụng File.exists()

File f = new File(filePathString); 
    if(f.exists()) 
    { 
    /* do something */ 
    } 
    else 
    { 
     file.mkdirs(); 
     //And your other stuffs goes here 
    } 

Note: exists() sẽ trở lại đúng với thư mục, quá

Nếu bạn muốn kiểm tra cho một tập tin đặc biệt tồn tại hoặc không bạn phải sử dụng File.isFile()

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

new File("C:/").exists() sẽ trả về true nhưng sẽ không cho phép bạn mở và đọc từ tệp dưới dạng tệp.

Sự cố trong mã của bạn là tên tệp của bạn là null.

Chỉnh sửa 2:

Hãy thử điều này:

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

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

Hoặc

hoặc trong onPreExecute() của AsyncTask bạn đặt hai câu lệnh này

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

Cảm ơn bạn đã trả lời.Xin vui lòng kiểm tra mã ở trên, nơi tôi đã kiểm tra các lớp donloadfile codition nhưng nó luôn luôn cho tôi msg như tập tin tồn tại nhưng tôi không được tạo ra. –

+0

+1 cho, Lưu ý: tồn tại() sẽ trả về true cho các thư mục, tôi quên điều đó. – user370305

+0

@PavanMore: kiểm tra xem tên tệp biến của bạn có null hay không. –

Các vấn đề liên quan