当前位置 : 主页 > 编程语言 > java >

读取文件并按行处理的优雅方式

来源:互联网 收集:自由互联 发布时间:2021-06-28
优雅的处理以行为读取单元的文件 public interface ReaderHelper { void process(String line);}public static void read(String path, ReaderHelper helper) { BufferedReader reader = null; try { reader = new BufferedReader(new InputSt
优雅的处理以行为读取单元的文件
public interface ReaderHelper {
    void process(String line);
}

public static void read(String path, ReaderHelper helper) {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            helper.process(line);
        }
    } catch (Exception e) {
        throw new RuntimeException("read file exception path[" + path + "].", e);
    } finally {
        close(reader);
    }
}


//用法
read(url, line -> {
    System.out.println(line);
});
优雅的读取并写入文件
public interface WriterHelper {
    default String process(String line) {
        return line;
    }
}

public static void readAndFlush(String readPath, String writePath, WriterHelper helper) {
    readAndWrite(readPath, writePath, true, helper);
}

public static void readAndAdd(String readPath, String writePath, WriterHelper helper) {
    readAndWrite(readPath, writePath, false, helper);
}

private static void readAndWrite(String readPath, String writePath, boolean isFlush, WriterHelper helper) {
    PrintWriter writer = null;
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(readPath), "UTF-8"));
        writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(writePath), "UTF-8"), isFlush);
        String line;
        while ((line = reader.readLine()) != null) {
            writer.println(helper.process(line));
        }
    } catch (Exception e) {
        throw new RuntimeException("read and write exception read path[" + readPath + "] write path[" + writePath + "].", e);
    } finally {
        close(reader);
        close(writer);
    }
}

// 使用
readAndFlush(readPath, writePath, new WriterHelper() {
    @Override
    public String process(String line) {
        line += "---Eugen";
        return line;
    }
});
网友评论