Files/Paths操作大文本数据的保存、修改、删除、获取
自己在做一个写小说的小系统,考虑到大文本不适合用数据库做持久化,所以写了这个工具来做文本文件形式的存储
util-articleFile.properties
里的parent.path
就是存储文本文件的目录的绝对路径
package net.add1s.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author pj.w@qq.com
*/
@Component
@PropertySource(value = "classpath:config/util-articleFile.properties")
public class ArticleFileUtil {
@Value("${parent.path}")
private String parentPath;
public String save(Long id, String data) throws IOException {
// 构造文件绝对路径
Path path = Paths.get(parentPath, id + ".txt");
// 创建文件
Files.createFile(path);
// 填充内容
BufferedWriter bufferedWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
// 返回保存的绝对路径
return path.toString();
}
public void update(Long id, String data) throws IOException {
// 获取原存储绝对路径
Path path = Paths.get(parentPath, id + ".txt");
// 覆盖原内容
BufferedWriter bufferedWriter = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
}
public boolean delete(Long id) throws IOException {
// 获取原存储绝对路径
Path path = Paths.get(parentPath, id + ".txt");
// 若文件存在就执行删除操作
return Files.deleteIfExists(path);
}
public String get(Long id) throws IOException {
// 获取目标文件存储绝对路径
Path path = Paths.get(parentPath, id + ".txt");
// 读取数据并返回
String line;
StringBuilder data = new StringBuilder();
BufferedReader bufferedReader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
while ((line = bufferedReader.readLine()) != null) {
// 追加内容,处理换行
data.append(line).append("\n");
}
return data.toString();
}
}