[英]Trouble with reading file from assets folder in Android
這個問題與此有關。 由於這是一個具體的問題,我在這里單獨提出了這個問題。 我已經嘗試創建一個文本文件“foo.txt”,將其讀入我的Activity中:
File file = new File("/assets/foo.txt");
if ( file.exists() ){
txtView.setText("Exists");
}
else{
txtView.setText("Does not exist");
}
“foo.txt”文件位於我的資源文件夾中,我已經驗證它存在於操作系統中。 我的TextView始終從上面的代碼中獲取文本“不存在”。 我試過去了
File file = new File("/assets/foo.txt");
Scanner in = new Scanner(file);
同樣,但這會產生以下內聯錯誤:“未處理的異常類型FileNotFoundException”。 Eclipse然后建議涉及try / catch,這會刪除錯誤,但它也不能正常工作。
我也嘗試將我的資源文件夾設置為“用作源文件夾”,但這沒有任何區別。 我也嘗試使用原始文件夾,因為有幾個人建議沒用。 我沒有選擇,真的需要幫助。 應該很容易......
另一種嘗試是去
AssetManager assetManager = getResources().getAssets();
InputStream is = assetManager.open("assets/foo.txt");
但是這會在第二行產生內聯錯誤:“未處理的異常類型IOException”。
在那種情況下,我與CommonsWare(這是安全方:)),但它應該是:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("foo.txt");
if ( inputStream != null)
Log.d(TAG, "It worked!");
} catch (IOException e) {
e.printStackTrace();
}
不要使用InputStream is = assetManager.open("assets/foo.txt");
您不能使用File
在運行時訪問assets/
。 您可以使用AssetManager
在運行時訪問assets/
,您可以通過getResources().getAssets()
。
嘗試這個 :
private AssetManager am;
am=getAssets();
InputStream inputStream = null ;
try
{
inputStream = am.open("read.txt");
}
catch (IOException e) {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.