Android開發 讀取assets下的TXT文字一直提示找不到檔案
阿新 • • 發佈:2019-01-31
發現了一個問題,以前寫的方法(點選開啟)讀取Assets目錄下的文字,今天弄過來發現一直找不到檔案,試了N多種辦法都不行,最後發編譯看了一下assets目錄下的TXT文字,發現tex文字沒有副檔名,怪不得找不到,這個文字是直接在AndroidStudio的assets目錄右鍵新建的,然後我刪除了這個檔案,在外面建立了文字複製進來呼叫方法就可以開啟。。。。
——————2017年2月24日01:16:58———————
下面有人要完整程式碼,讀取程式碼如下:
String content = FileUtils.readAssetsTextReturnStr(AgreementActivity.this , "agreement");
/**
* 讀取assets下的txt檔案,返回utf-8 String
* @param context
* @param fileName 不包括字尾
* @return
*/
public static String readAssetsTextReturnStr(Context context,String fileName){
try {
//Return an AssetManager instance for your application's package
InputStream is = context.getAssets().open(fileName+".txt");
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer, "utf-8");
// Finally stick the string into the text view.
return text;
} catch (IOException e) {
// Should never happen!
// throw new RuntimeException(e);
e.printStackTrace();
}
return "";
}
—————————–2017年4月8日12:14:23—————————–