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.Charset; 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 FileUtil { public static Path path(String first, String... more) { return Paths.get(first, more); } public static List readUtf8Lines(Path path) { return readLines(path, StandardCharsets.UTF_8); } public static List readNonEmptyUtf8Lines(Path path) { List lines = readUtf8Lines(path); List result = new ArrayList(); for (String line : lines) { if (line != null && line.trim().length() > 0) { result.add(line); } } return result; } public static List readLines(Path path, Charset charset) { List result = new ArrayList(); try (BufferedReader reader = Files.newBufferedReader(path, charset)) { for (String line; (line = reader.readLine()) != null;) { result.add(line); } } catch (IOException e) { throw new UncheckedIOException("读取文件失败:" + path.toAbsolutePath(), e); } return result; } public static String readUtf8Text(Path path) { List lines = readUtf8Lines(path); StringBuilder builder = new StringBuilder(); for (int i = 0; i < lines.size(); i++) { builder.append(lines.get(i)); if (i < lines.size() - 1) { builder.append(System.lineSeparator()); } } return builder.toString(); } public static void writeUtf8Text(Path path, String content) { try { Path parent = path.getParent(); if (parent != null) { Files.createDirectories(parent); } try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { writer.write(content); } } catch (IOException e) { throw new UncheckedIOException("写入文件失败:" + path.toAbsolutePath(), e); } } }