//path: 路径
//Msg: 要写入的内容
//isCover: 是否覆盖原有内容, true 覆盖, false 新增
public static boolean writeFile(String path, String Msg, boolean isCover) {
try {
File file = new File(path);
if (file.isDirectory()) {
//写入文件失败, 写入文件只有路径没有文件名
return false;
}
//获取索引路径
String directory = cutStringTailByCut(path, ‘/’);
createDirsPath(directory);//创建索引(没有则创建, 有不创建)
FileOutputStream fileOutput = new FileOutputStream(file, !isCover);
fileOutput.write(Msg.getBytes(“utf-8”));
fileOutput.close();
return true;
} catch (Exception e) {
e.printStackTrace();
//写入记录失败,请检查是否打开存储权限
return false;
}
}
//创建路径, 如果路径已存在返回true, 不存在创建成功返回true, 创建失败返回false, 其他异常情况返回false
//可创建多层路径
public static boolean createDirsPath(String dirPath) {
try {
File file = new File(dirPath);//读取SD卡文件
if (!file.isDirectory()) {
return file.mkdirs();
}
return true;
} catch (Exception e) {
e.printStackTrace();
//创建路径失败,请检查是否打开存储权限;
return false;
}
}
//通过分隔符 cut, 去掉 str 的尾巴
public static String cutStringTailByCut(String str, char cut) {
if (str == null)
return null;
char[] C = str.toCharArray();
String S = “”;
int noteA = -1;
for (int a = C.length - 1; a >= 0; a–) {
if (C[a] == cut) {
noteA = a;
break;
}
}
if (noteA == -1)
return str;
for (int a = 0; a < noteA; a++) {
S += C[a];
}
return S;
}
Android studio 向手机存储写入txt内容
最新推荐文章于 2023-07-01 19:45:16 发布