[英]How to get right path files in android
我的代碼如下:
Scanner sc = null;
try {
sc = new Scanner(new File("assets/mainmenu/readSourceFile.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
System.out.println(e1.toString());
e1.printStackTrace();
}
然后,logcat顯示異常java.io.FileNotFoundException
我怎樣才能找到我的檔案? 我試過了
sc = new Scanner(new File("mainmenu/readSourceFile.txt"));
但是,它仍然拋出FilenotFoundException
我的文件位於文件夾assets / mainmenu / readSourceFile.txt中
我試試這個::
private InputStream is;
try {
is = this.getResources().getAssets().open("mainmenu/readSourceFile.txt");
} catch (IOException e) {
e.toString();
}
我使用getAssets來訪問android中的資產文件。 但是,如果我使用InputStream
,我怎么能想讀取文本文件
你試試這個......希望它能奏效
sc = new Scanner(new File("file:///android_asset/mainmenu/readSourceFile.txt");
編輯嘗試這個
AssetFileDescriptor descriptor = getAssets().openFd("mainmenu/readSourceFile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());
從此處復制資產文件夾路徑
您無法訪問Android應用程序的assets
文件夾,就好像它們是文件系統上的常規文件一樣(提示:它們不是)。 相反,您需要在活動/應用程序上下文中使用AssetManager
.Call getAssets()
來獲取AssetManager
。
完成后,您可以使用open("mainmenu/readSourceFile.txt")
來獲取InputStream
。
您現在可以像閱讀其他任何內容一樣閱讀此InputStream
。 Apache Commons IO是一個很棒的庫,用於處理輸入和輸出流。 根據您想要獲取數據的方式,您可以嘗試:
將整個文件讀入String:
try { String contents = IOUtils.toString(in); } finally { IOUtils.closeQuietly(in); }
將整個文件讀入一個字符串列表,每行一個:
try { List<String> lines = IOUtils.readLines(in); } finally { IOUtils.closeQuietly(in); }
一次遍歷文件一行:
try { LineIterator it = IOUtils.lineIterator(in, "UTF-8"); while (it.hasNext()) { String line = it.nextLine(); // do something with line } } finally { IOUtils.closeQuietly(in); }
我遇到過同樣的問題。 我注意到該文件不應包含層次結構。 如果將來有人遇到同樣的問題,這對我有用。 `
InputStream is=null;
try {
is=activity.getAssets().open("fileInAssets.dat");
} catch (IOException e1) {
Log.e(TAG, "Erro while openning hosts file.");
e1.printStackTrace();
}
`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.