android建立文件夹、生成文件并写入内容
原文连接:https://www.cnblogs.com/liqw/p/4014760.html。
用于开发测试时记录日志,特别是记录后台服务运行的日志,特别好用。
下面是根据自己的情况,改了一小部分代码。
结果图:
代码:
// 将字符串写入到文本文件中
public static void writeTxtToFile(String strcontent) {
if (!isSaveLog) return;//判断是否写入日志
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());
String str = formatter.format(curDate);
String filePath = "/sdcard/ATest/";
String fileName = "log.txt";
//生成文件夹之后,再生成文件,不然会出错
makeFilePath(filePath, fileName);
String strFilePath = filePath + fileName;
// 每次写入时,都换行写
String strContent = strcontent + "--" + str + "\r\n";
try {
File file = new File(strFilePath);
if (!file.exists()) {
Log.d("TestFile", "Create the file:" + strFilePath);
file.getParentFile().mkdirs();
file.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(strContent.getBytes());
raf.close();
} catch (Exception e) {
Log.e("TestFile", "Error on write File:" + e);
}
}
// 生成文件
private static File makeFilePath(String filePath, String fileName) {
File file = null;
makeRootDirectory(filePath);
try {
file = new File(filePath + fileName);
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
// 生成文件夹
private static void makeRootDirectory(String filePath) {
File file = null;
try {
file = new File(filePath);
if (!file.exists()) {
file.mkdir();
}
} catch (Exception e) {
Log.i("error:", e + "");
}
}
最后在本项目app或自定义模块下的Manifest.xml添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>