写入:writeToFile
读取:getContent
删除文件:delFile
删除文件夹:delFolder
删除文件夹及其内容:delAllFile
/**
* 将内容字段存到文本文件中去
*
* @param fileList
*/
private void writeToFile(List<Map<String, String>> fileList) {
BufferedWriter demoWriter;
// 存入文档
for (int i = 0; i < fileList.size(); i++) {
String key = fileList.get(i).get("id") + "_" + fileList.get(i).get("content");
// 得到文件路径
String filePath = fileList.get(i).get("filePath");
try {
File file = new File(filePath);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// 写数据
demoWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "utf-8"));
demoWriter.write(key + "\n");
demoWriter.close();
} catch (IOException e) {
LOG.error(String.format("内容文件保存异常, 异常信息为:%s", e.getMessage()));
}
}
}
/**
* 得到文章内容
*
* @param id
* @param historyKeysPath
* @return
* @throws IOException
*/
private String getContent(Long id, String historyKeysPath) throws IOException {
String content = null;
// 得到文件路径
// String historyKeysPath="D:\\"+year+File.separator+month+File.separator+day+"\\weibo.txt";
// 根据id读取文件内容
// String historyKeysPath="test_weibo.txt";
File historyFile = new File(historyKeysPath);
if (historyFile.exists()) {
FileInputStream fis = new FileInputStream(historyKeysPath);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
// System.out.println("line:"+line);
if (line.split("_")[0].equalsIgnoreCase(String.valueOf(id))) {
content = line.split("_")[1];
}
}
reader.close();
}
return content;
}
/**
* 删除文件
*
* @param fileName
* 文件名称
* @return
*/
public static boolean delFile(String filePath) {
Boolean bool = false;
// filenameTemp = path+fileName+".txt";
File file = new File(filePath);
try {
if (file.exists()) {
file.delete();
bool = true;
}
} catch (Exception e) {
}
return bool;
}
/**
* 删除文件夹
*
* @param folderPath
*/
private static void delFolder(String folderPath) {
try {
delAllFile(folderPath); // 删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); // 删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除指定文件夹下的所有文件
*
* @param path
* @return
*/
private static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);// 再删除空文件夹
flag = true;
}
}
return flag;
}