//读取txt文件, 返回值永远不为null
//注意要有存储权限
public static String readFile(String path) {
String result;
try {
File file = new File(path);//先读取info.txt
if (!file.exists()) {
return “”;
}
int length = (int) file.length();
byte[] buff = new byte[length];
FileInputStream fileInput = new FileInputStream(file);
fileInput.read(buff);
result = new String(buff, “UTF-8”);
fileInput.close();
return result;
} catch (Exception e) {
e.printStackTrace();
showTip(“读取文件失败,请检查是否打开存储权限”);
logRed(“读取文件失败, 路径:” + path);
return “”;
}
}
Android studio 读取txt文件内容
最新推荐文章于 2025-10-05 09:00:10 发布
本文介绍了一种在Android环境中读取TXT文件的方法,确保了即使在文件不存在的情况下也能返回空字符串,避免程序崩溃。该方法使用FileInputStream读取文件内容,并以UTF-8编码解析,适用于需要读取本地存储文件的场景。
1022

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



