2013-02-06 61 views
0

我正在嘗試編寫一些代碼將文件從服務器直接傳輸到Android外部存儲系統。如何從Android應用程序寫入外部存儲?

private void streamPDFFileToStorage() { 
    try { 
     String downloadURL = pdfInfo.getFileServerURL(); 
     URL url = new URL(downloadURL); 
     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
     InputStream pdfFileInputStream = new BufferedInputStream(httpURLConnection.getInputStream()); 
     File pdfFile = preparePDFFilePath(); 
     OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile)); 
     byte[] buffer = new byte[8012]; 
     int bytesRead; 
     while ((bytesRead = pdfFileInputStream.read(buffer)) != -1) { 
      fileOutputStream.write(buffer, 0, bytesRead); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

private File preparePDFFilePath() { 
    File sdCard = Environment.getExternalStorageDirectory(); 
    File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2"); 
    dir.mkdirs(); 
    File file = new File(dir, "filename"); 
    return file; 
    /* 
    String pdfFileDirectoryPath = ApplicationDefaults.sharedInstance().getFileStorageLocation() + pdfInfo.getCategoryID(); 
    File pdfFileDirectory = new File(pdfFileDirectoryPath); 
    pdfFileDirectory.mkdirs(); 
    return pdfFileDirectoryPath + "/ikevin" + ".pdf"; 
    */ 
} 

它使越來越 「沒有這樣的文件或目錄」 的一個例外,在

"OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));"

我如何寫文件?我的代碼有什麼問題? (?還有,我不使用Context.getExternalFilesDir()因爲我不知道如何從我的控制器邏輯代碼獲取上下文任何人都可以提出建議,如果這是更好的解決方案)

+1

您是否擁有AndroidManifest.xml中的權限WRITE_EXTERNAL_STORAGE? –

+0

是的,我確實(我查過)。 – ikevin8me

+0

是的,那是魔鬼! – ikevin8me

回答

2

new File正在返回一個文件對象而不是文件。在打開流之前,您可能會先創建一個文件。試試這個

File pdfFile = preparePDFFilePath(); 
boolean isCreated = pdfFile.createNewFile(); 
if(isCreated){ 
    OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile)); 
} 
+0

它仍然無法使用沒有這樣的文件或目錄IOException。 – ikevin8me

+0

引發異常「file.createNewFile();」 – ikevin8me

+0

對不起,它工作。這是明顯的事情。我以爲我檢查了它,但那是最後的問題。 createNewFile()幫助。 – ikevin8me

0

此代碼:

String root = Environment.getExternalStorageDirectory().toString(); 
    File dir = new File(root + "/dir1");  
    dir.mkdirs();