/**
* 读取assets下的txt文件,返回utf-8 String
* @param context
* @param fileName 不包括后缀
* @return
*/
public static String readAssetsTxt(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 "读取错误,请检查文件名";
}
直接上代码简单粗暴
本文提供了一个简单的Java方法,用于从Android应用的assets目录中读取指定的txt文件,并将其内容作为UTF-8编码的字符串返回。该方法适用于需要加载文本资源的应用场景。
1255

被折叠的 条评论
为什么被折叠?



