将字符串以文本的形式保存到本地
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
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 + "\r\n";
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");
微语
据说看完点赞可以避开社会90%的黑暗潜规则.
|