我正在尝试编写一些代码以将文件从服务器直接流式传输到 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()
,因为我不知道如何从我的控制器逻辑代码中获取上下文。谁能建议这是否是更好的解决方案?)