2012-09-25 64 views
1

我正在通過Web服務提供的URL幫助從服務器下載文件。 我對每個設備版本都很成功,但在OS 4.1設備中出現異常。 我使用以下代碼:保存文件到android的內存?

public static Boolean DownloadFile(String fileURL, File directory) { 
       try { 

         FileOutputStream f = new FileOutputStream(directory); 
         URL u = new URL(fileURL); 
         HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
         c.setRequestMethod("GET"); 
         c.setDoOutput(true); 
         c.connect(); 

         InputStream in = c.getInputStream(); 

         byte[] buffer = new byte[1024]; 
         int len1 = 0; 
         while ((len1 = in.read(buffer)) > 0) { 
           f.write(buffer, 0, len1); 
         } 
         f.close(); 
         return true; 
       } catch (Exception e) { 
         e.printStackTrace(); 
         return false; 
       } 
     } 

我正在java.io.FileNotFoundException在線路c.getInputStream(); 請建議我解決這個問題。

我打算使用內部存儲器,但作爲用戶不能訪問內部存儲器。

回答

6

試試這個代碼: 注意這種情況下創建文件可能是一個活動/ ApplicationContext中的/ etc

public boolean downloadFile(final String path) 
    { 
     try 
     { 
      URL url = new URL(path); 

      URLConnection ucon = url.openConnection(); 
      ucon.setReadTimeout(5000); 
      ucon.setConnectTimeout(10000); 

      InputStream is = ucon.getInputStream(); 
      BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); 

      File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/yourfile.png"); 

      if (file.exists()) 
      { 
       file.delete(); 
      } 
      file.createNewFile(); 

      FileOutputStream outStream = new FileOutputStream(file); 
      byte[] buff = new byte[5 * 1024]; 

      int len; 
      while ((len = inStream.read(buff)) != -1) 
      { 
       outStream.write(buff, 0, len); 
      } 

      outStream.flush(); 
      outStream.close(); 
      inStream.close(); 

     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
      return false; 
     } 

     return true; 
    } 
-2

試試這個代碼:

String root = Environment.getExternalStorageDirectory().toString(); 
File myDir = new File(root + "/saved_images");  
myDir.mkdirs(); 
Random generator = new Random(); 
int n = 10000; 
n = generator.nextInt(n); 
String fname = "Image-"+ n +".jpg"; 
File file = new File (myDir, fname); 
if (file.exists()) file.delete(); 
try { 
     FileOutputStream out = new FileOutputStream(file); 
     finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); 
     out.flush(); 
     out.close(); 

} catch (Exception e) { 
     e.printStackTrace(); 
} 

,並添加清單:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
+3

他問如何將文件保存在內存中,而不是外部存儲器... – quantm