我正在嘗試編寫一些代碼將文件從服務器直接傳輸到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()
因爲我不知道如何從我的控制器邏輯代碼獲取上下文任何人都可以提出建議,如果這是更好的解決方案)
您是否擁有AndroidManifest.xml中的權限WRITE_EXTERNAL_STORAGE? –
是的,我確實(我查過)。 – ikevin8me
是的,那是魔鬼! – ikevin8me