如何从assets文件夹创建文件对象?

8
我正试图从我的资产文件夹中读取一个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对象或让我知道如何获取文件的确切路径。我也尝试了file:///android_asset/Introduction.pdf,但没有成功。我还尝试了Image.png,但从来没有得到过file.exists()的成功。我正在使用Android Studio的Mac版本。谢谢。


2
可能是 https://dev59.com/pmkw5IYBdhLWcg3w8fBJ 的重复问题。 - Monish Kamble
我正在尝试创建“文件”,而上面的代码创建了InputStream。 - Zulqarnain Mustafa
请查看此链接:https://dev59.com/O2Qn5IYBdhLWcg3wIUFn,这与您想要实现的类似。 - Hasif Seyd
3个回答

11
从资产中获取输入流并将其转换为文件对象。
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); }

6

Kotlin 中,将资产存储为缓存文件的短转换器:

fun fileFromAsset(name: String) : File =
    File("$cacheDir/$name").apply { writeBytes(assets.open(name).readBytes()) }

cacheDirthis.getCacheDir() 的简写,应该已经为您预定义好了。


3

你能试试这段代码吗?

AssetManager am = getAssets();
InputStream inputStream = am.open("Indroduction.pdf");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File("new FilePath");
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

然后尝试使用以下方法:

File file = new File("new file path");

if (file.exists())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接