Zul*_*ain 3 java pdf android android-studio
我正在尝试从资产文件夹中读取pdf文件,但我不知道如何获取pdf文件的路径。我右键单击pdf文件,然后选择“复制路径”并粘贴
这是我的代码:
File file = new File("/Users/zulqarnainmustafa/Desktop/ReadPdfFile/app/src/main/assets/Introduction.pdf");
if (file.exists()){
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
this.startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application available to view PDF", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this, "File path not found", Toast.LENGTH_LONG).show();
}
Run Code Online (Sandbox Code Playgroud)
我总是找不到文件,请帮助我创建File对象,或者让我知道如何获取我也尝试过file:///android_asset/Introduction.pdf
但没有成功的文件的确切路径。我也尝试使用Image.png,但从未成功过file.exists()。我正在使用Mac版本的Android Studio。谢谢
Kotlin中的短转换器(将资源存储为缓存文件):
fun fileFromAsset(name: String) : File =
File("$cacheDir/$name").apply { writeBytes(assets.open(name).readBytes()) }
Run Code Online (Sandbox Code Playgroud)
cacheDir
只是简写this.getCacheDir()
,应该为您预定义。
从资产获取输入流并将其转换为文件对象。
File f = new File(getCacheDir()+"/Introduction.pdf");
if (!f.exists())
try {
InputStream is = getAssets().open("Introduction.pdf");
byte[] buffer = new byte[1024];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6024 次 |
最近记录: |