package cn.edu.bjut.textmining.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** UTF-8文件读写;数据路径相对于项目根目录。 */ public final class Chapter4Files { private Chapter4Files() {} public static Path data(String name) { return Paths.get("data", "chapter4", name); } public static Path output(String name) { return Paths.get("output", "chapter4", name); } public static List read(Path path) { List lines = new ArrayList(); try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { for (String line; (line = reader.readLine()) != null; ) { lines.add(line); } } catch (IOException e) { throw new UncheckedIOException("读取文件失败:" + path.toAbsolutePath(), e); } return lines; } public static void write(Path path, String text) { try { Files.createDirectories(path.getParent()); BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8); writer.write(text); } catch (IOException e) { throw new UncheckedIOException("保存文件失败:" + path.toAbsolutePath(), e); } } }