无法打开在Android应用程序的临时文件夹中创建的文件 - 文件不存在或无法读取

时间:2015-03-17 08:10:03

标签: android

当我运行下面的代码时,我得到一个提示,用适当的阅读器打开文件,但文件没有显示。

我是Android App开发的新手,非常感谢任何帮助。

URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);

//connect
urlConnection.connect();

file = File.createTempFile("Christo", ".pdf");
fileOutput = new FileOutputStream(file);

//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();

//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();

runOnUiThread(new Runnable() {
    public void run() {
        pb.setMax(totalSize);
    }
});

//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength;

while ((bufferLength = inputStream.read(buffer)) > 0) {
    fileOutput.write(buffer, 0, bufferLength);
    downloadedSize += bufferLength;
    // update the progressbar //
    runOnUiThread(new Runnable() {
        public void run() {
            pb.setProgress(downloadedSize);
            float per = ((float) downloadedSize / totalSize) * 100;
            cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int) per + "%)");
        }
    });
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
    public void run() {
        // do not close progressbar
    }
});

} catch (final MalformedURLException e) {
    showError("Error : MalformedURLException " + e);
    e.printStackTrace();
} catch (final IOException e) {
    showError("Error : IOException " + e);
    e.printStackTrace();
} catch (final Exception e) {
    showError("Error : Please check your internet connection " + e);
}

Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);

2 个答案:

答案 0 :(得分:0)

我认为在创建文件时应该是

file = File.createTempFile("Christo", "pdf");

。 [dot]不是必需的

答案 1 :(得分:0)

您正在为其他应用程序创建内部-private-memory无法访问的文件。而是在外部存储器中创建它。在清单中询问外部写入权限。