0

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

4

2 回答 2

2

new File正在返回一个文件对象而不是文件。您可能想在打开一个流之前创建一个文件。试试这个

File pdfFile = preparePDFFilePath();
boolean isCreated = pdfFile.createNewFile();
if(isCreated){
   OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
}
于 2013-02-06T19:15:12.720 回答
0

此代码有效:

    String root = Environment.getExternalStorageDirectory().toString();
    File dir = new File(root + "/dir1");    
    dir.mkdirs();
于 2013-02-06T19:10:26.467 回答