2011-10-19 8 views
11

Voglio scaricare pdf dal server e archiviare su sdcard. Provo qualcosa di simile al seguente codice ma non andrà in altre condizioni, dato che non sono ancora stato creato un file che fornirà MSG come file. Perché è così??Come verificare il file esistente o meno e se non si crea un nuovo file in sdcard in attività asincrona

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

In cui l'esecuzione altra condizione non fatto? – user370305

+0

L'ho già fatto, ma il problema è che verrà sempre all'interno se condizione del metodo doInBackground() poiché non sono stato creato il file. –

+0

Se hai risolto bene, altrimenti guarda la mia risposta modificata. – user370305

risposta

27

È possibile controllare se file esiste o meno utilizzando File.exists()

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

Nota: exists() restituirà true per le directory, anche

Se si desidera verificare la presenza di un particolare file che esiste o non devi usare File.isFile()

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

new File("C:/").exists() restituirà true ma non ti permetterà di aprire e leggere da esso come un file.

Il problema nel codice è il nome file è nullo.

Edit 2:

Prova questo:

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

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

O

o in OnPreExecute() di AsyncTask mettere questo due affermazioni

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

Grazie per la risposta.Si prega di controllare sopra il codice in cui ho già controllato la classe di donloadfile di codifica, ma mi dà sempre msg come file esiste ancora non sono stato creato. –

+0

+1 per, Nota: esiste() restituisce true per le directory, l'ho dimenticato. – user370305

+0

@PavanMore: controlla se il nome file della variabile è nullo o meno. –

Problemi correlati