Android studio 向手机存储写入txt内容

//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;
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值