- 简单说明
- 基于jdk1.8版本编写、测试;
- 使用jdk1.7新语法try-with-resource,自动回收资源;
- 支持情况
- 支持读写操作;
- 写入支持新建写入和追加写入 两种方式;
- 读取支持合并读取、分行读取、带处理函数的分行读取 三种方式;
- 具体代码
import lombok.extern.slf4j.Slf4j; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; /** * 文件读写工具类 * * @author 杨彭伟 * @date 2019-05-14 14:54 */ @Slf4j public class FileUtil { /** * 读取文件 * * @param filePath 文件路径 * @return 文件内容 */ public static String readFile(String filePath) { StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader br = Files.newBufferedReader(Paths.get(filePath))) { String line; while ((line = br.readLine()) != null) { stringBuilder.append(line); log.info(line); } return stringBuilder.toString(); } catch (IOException e) { log.error("readFile", e); } return null; } /** * 单行读取文件,并由处理函数 * @param filePath 文件路径 * @param consumer 带有字符串参数的处理函数 */ public static void readFile(String filePath, Consumer<String> consumer) { try (BufferedReader br = Files.newBufferedReader(Paths.get(filePath))) { String line; while ((line = br.readLine()) != null) { log.info(line); consumer.accept(line); } } catch (IOException e) { log.error("readFile", e); } } /** * 读取文件的所有行,并用List返回 * * @param filePath 文件路径 * @return 文件内容 */ public static List<String> readFileAllLines(String filePath) { try (BufferedReader br = Files.newBufferedReader(Paths.get(filePath))) { List<String> result = new ArrayList<>(); String line; while ((line = br.readLine()) != null) { log.info(line); result.add(line); } return result; } catch (IOException e) { log.error("readFileAllLines", e); } return null; } /** * 创建新文件写入 * * @param filePath 文件路径 * @param contents 要写入的内容 * @return 是否写入成功 */ public static boolean writeNewFile(String filePath, List<String> contents) { try (FileWriter writer = new FileWriter(filePath); BufferedWriter bw = new BufferedWriter(writer)) { for (String content : contents) { bw.write(content); bw.newLine(); } return true; } catch (IOException e) { log.error("writeNewFile", e); } return false; } /** * 没有文件就创建文件写入,有就追加到文件的后面写入 * * @param filePath 文件路径 * @param contents 要写入的内容 * @return 是否写入成功 */ public static boolean writeAppendFile(String filePath, List<String> contents) { try (FileWriter writer = new FileWriter(filePath, true); BufferedWriter bw = new BufferedWriter(writer)) { for (String content : contents) { bw.append(content); bw.newLine(); } return true; } catch (IOException e) { log.error("writeAppendFile", e); } return false; } }
文件读写工具类(新建写入、追加写入)
于 2019-05-14 17:14:30 首次发布