2013-03-12 81 views
0

我試圖完成兩件事情在我的Android應用:從服務器如何從服務器下載文件並將其顯示在視圖中?

  • 下載文件(PDF,圖像和HTML)
  • 下載後的文件,從服務器,並顯示在Android中保存的所有文件Tab view

我的問題是,我如何從服務器下載文件並將其顯示在我的應用程序中?

我下載的代碼如下所示:

public void downloadFiles() { 

     try { 

      URL url = new URL ("http://google.com/nexuspads.png"); 
      HttpURLConnection c = (HttpURLConnection) url.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setDoOutput(true); 
      c.connect(); 

      String PATH = Environment.getExternalStorageDirectory() + "/download/" ; 

      Log.v ("LOG_TAG" , "PATH: " + PATH); 
      File file = new File (PATH); 
      file.mkdirs(); 

      String fileName = "image.png"; 

      File outputFile = new File (file, fileName); 
      FileOutputStream fos = new FileOutputStream(outputFile); 

      InputStream is = c.getInputStream(); 

      byte[] buffer = new byte [1024]; 

      int len1 = 0 ; 

      while ((len1 = is.read(buffer)) != -1){ 

       fos.write (buffer, 0, len1); 
      } 

      fos .close(); 
      is.close(); 

     }catch (IOException e) { 
      Log.d ("LOG_TAG2 ", "Error " + e); 
//   Toast.makeText(,"error " +e.toString(), Toast.LENGTH_LONG).show();  
     } 

    } 
+0

我試圖從服務器上下載文件,現在我tryig找到一種方法來在android應用程序活動中使此文件視圖。 – star18bit 2013-03-12 03:50:41

回答

0

列出文件夾中的文件可以如下進行..

String path = Environment.getExternalStorageDirectory().toString()+"/YOUR folder here/"; 
      File f = new File(path);   
      final File listfile[] = f.listFiles();  
      String[] fileList = new String[listfile.length]; 
      for (int i=0; i < listfile.length; i++)  
      { 
       fileList[i] = listfile[i].getName(); 
       Log.v("Files", "FileName:" + listfile[i].getName()); 
      } 

你再會顯示警告對話框的結果或在ListView中。

相關問題