Android字符串数据保存到本地txt文件(FileUtils)
持续摸鱼中...
将字符串以文本的形式保存到本地
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* File tools
*
* @author Abner_阿锋
* @version 1.0
* @date 2021/12/8
*/
public class FileUtils {
private static final String TAG = "FileUtils";
// 将字符串写入到文本文件中
public static void writeTxtToFile(String content, String filePath, String fileName) {
//生成文件夹之后,再生成文件,不然会出错
makeFile(filePath, fileName);
String mFilePath = filePath + fileName;
// 每次写入时,都换行写
String mContent = content + "rn";
try {
File file = new File(mFilePath);
if (!file.exists()) {
LogUtils.logD(TAG, "创建文件: " + mFilePath);
file.getParentFile().mkdirs();
file.createNewFile();
}
RandomAccessFile mRandomAccessFile = new RandomAccessFile(file, "rwd");
mRandomAccessFile.seek(file.length());
mRandomAccessFile.write(mContent.getBytes());
mRandomAccessFile.close();
} catch (IOException e) {
LogUtils.logD(TAG, "写入错误: " + e.toString());
}
}
//生成文件
public static File makeFile(String filePath, String fileName) {
File file = null;
makeDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
file.createNewFile();
}
} catch (IOException e) {
LogUtils.logD(TAG, "生成文件错误: " + e.toString());
}
return file;
}
//生成文件夹
public static void makeDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
} catch (Exception e) {
LogUtils.logD(TAG, "生成文件夹错误: " + e.toString());
}
}
}
调用
String mContent = "阿锋真帅,阿锋真帅,阿锋真帅,重要的事情说三遍";
String mPath ="/sdcard/data/data/";
FileUtils.writeTxtToFile(mContent, mPath, "afeng.txt");
微语
据说看完点赞可以变帅?
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
二维码