我想从URL下载文件并将其保存到内部存储器中。一旦文件保存在内部存储器中,我想触发一个Intent在应用程序中打开它。
**Following is the code to download the file and save in internal memory:**
private void getPDFContent(String myUrl, String sfilename) {
try {
FileOutputStream fos = this.openFileOutput(sfilename,Context.MODE_PRIVATE);
URL u = new URL(myUrl);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
fos.write(buffer, 0, len1);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
**Following is the code to read:**
public void readInternalStorageOption() {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
String filePath = getApplication().getFilesDir().getAbsolutePath()
+ File.separator + "test.pdf";
File f = new File(filePath);
if (f.exists()) {
Uri internal = Uri.fromFile(f);
intent.setDataAndType(internal, "application/pdf");
}
startActivity(intent);
} catch (NullPointerException ex) {
}
}
问题是该文件已成功保存,但当我尝试通过意图打开它时,我收到一个错误,即该文件无法打开。请为此建议任何解决方案。