繁体   English   中英

如何从资产文件夹创建文件对象?

[英]How to create File object from assets folder?

我正在尝试从我的资产文件夹中读取 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();
    }

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

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

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

你能试试这个代码吗

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

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

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

cacheDir只是this.getCacheDir()简写,应该为您预定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM