在开发过程中,我们经常会使用把一些信息保存到本地的内存当中,今天小编就给大家展示一个简单的文件操作的工具类,后续将会继续完善。废话不多少说,我们直接看代码。
public class FileUtils {
private static final String mLogPath = "/utils/files";
//创建文件
public static void createFile(String name) {
File file = new File(Environment.getExternalStorageDirectory() + mLogPath);
try {
if (!file.exists()) {
file.mkdirs();
}
file = new File(Environment.getExternalStorageDirectory() + mLogPath + "/" + name);
if (!isLogExist(file)) {
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addLog(String fileName, String conent) {
createFile(fileName + ".txt");
fileName = Environment.getExternalStorageDirectory() + mLogPath + "/" + fileName + ".txt";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间
String str = formatter.format(curDate);
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName, true)));
out.write(str+conent + "\r\n".getBytes("gbk"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 检查文件是否存在
*
* @param file
* @return
*/
private static boolean isLogExist(File file) {
File tempFile = new File(Environment.getExternalStorageDirectory() + mLogPath);
File[] files = tempFile.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[0].getName().trim().equalsIgnoreCase(file.getName())) {
return true;
}
}
}
return false;
}
//获取所有文件夹的名字
public static String[] getFileName(String path) {
File file = new File(path);
String[] fileName = file.list();
return fileName;
}
}