簡體   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