java - 如何从 Assets 文件夹创建文件对象?

标签 java android android-studio pdf

我正在尝试从我的 Assets 文件夹中读取 pdf 文件,但我不知道如何获取 pdf 文件的路径。 我右键单击 pdf 文件并选择“复制路径”并粘贴它 enter image description here

这是我的代码的另一个屏幕截图: enter image description here

这是我的代码:

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();
    }

我总是找不到文件,帮助我创建文件对象或让我知道如何获得文件的确切路径我也尝试过 file:///android_asset/Introduction.pdf 但没有成功。我也尝试过使用 Image.png 但从未获得 file.exists() 成功。我正在使用 Mac 版本的 Android Studio。谢谢

最佳答案

从 Assets 中获取输入流并将其转换为文件对象。

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); }

关于java - 如何从 Assets 文件夹创建文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340422/

相关文章:

java - 单词词典的哈希效率加倍

java - 使用媒体播放器时出现奇怪的错误

java - 如何使用 android 的 MediaRecorder 检测文件何时达到其最大大小?

android - Android Studio-Gradle同步失败

java - 1/0 是合法的 Java 表达式吗?

java - 在 JavaFX 中调整图像的不透明度

java - 如何在多层环境(REST + EJB + Core)中使用JPA EclipseLink连接DB?

android - 如何在方向更改时保留所选微调器/下拉项的状态?

java - 使图像文件夹在项目中可用

Android Studio list 合并失败