gpt4 book ai didi

android - 如何读取保存到设备内部存储的PDF文件?

转载 作者:行者123 更新时间:2023-11-30 03:43:24 25 4
gpt4 key购买 nike

我正在使用以下代码从设备的内部存储中下载和读取 PDF 文件。

我能够成功将文件下载到目录:

data/data/packagename/app_books/file.pdf

但我无法使用 Adob​​e Reader 等 PDF 阅读器应用程序阅读该文件。

下载文件代码

//Creating an internal dir;
File mydir = getApplicationContext().getDir("books", Context.MODE_WORLD_READABLE);

try {
File file = new File(mydir, outputFileName);
URL downloadUrl = new URL(url);
URLConnection ucon = downloadUrl.openConnection();
ucon.connect();

InputStream is = ucon.getInputStream();

FileOutputStream fos = new FileOutputStream(file);

byte data[] = new byte[1024];

int current = 0;
while ((current = is.read(data)) != -1) {
fos.write(data, 0, current);
}
is.close();
fos.flush();
fos.close();
isFileDownloaded=true;
} catch (IOException e) {
e.printStackTrace();
isFileDownloaded = false;
System.out.println(outputFileName + " not downloaded");
}
if (isFileDownloaded)
System.out.println(outputFileName + " downloaded");
return isFileDownloaded;

读取文件的代码

PackageManager packageManager = getPackageManager();

Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");

List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);

try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);

File fileToRead = new File(
"/data/data/com.example.filedownloader/app_books/Book.pdf");
Uri uri = Uri.fromFile(fileToRead.getAbsoluteFile());

intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception ex) {
Log.i(getClass().toString(), ex.toString());
Toast.makeText(MainActivity.this,
"Cannot open your selected file, try again later",
Toast.LENGTH_SHORT).show();
}

一切正常,但阅读器应用程序显示“文件路径无效”

最佳答案

您的路径仅对您的应用有效。将文件放在其他应用程序可以“看到”的地方。使用 GetExternalFilesDir() 或 getExternalStorageDirectory()。

关于android - 如何读取保存到设备内部存储的PDF文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15405775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com