Java IO

使用 InputStream, OutPutStream 操作 byte

使用 Reader, Write 操作字符

Reader, Writer 与 InputStream, OutputStream 关系

Java NIO 架构图

NIO 提供了 DirectByteBuff, 并用装饰器模式实现了 byte 到 primitive 转换。

Java 7 工具类 Files

var path = Paths.get("/Users/xuzeng/Documents/usr/Java/private/AnatomyQuark/hack-jdk13/files/appendable.txt");
Files.lines(path).forEach(System.out::println);
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
byte[] bytes = Files.readAllBytes(path);

BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
String line = reader.readLine();
char[] fragment = new char[10];
reader.read(fragment, 0, 10);

InputStream in = Files.newInputStream(path);
byte[] raw = new byte[100];
in.read(raw);

DirectByteBuff

import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

private void append() throws FileNotFoundException, IOException {
    String msg = "{append mimic msg}\\n";
    FileChannel fc = new RandomAccessFile(LOG_FILE_PATH, "rw").getChannel();
    MappedByteBuffer mbf = fc.map(FileChannel.MapMode.READ_WRITE, 0, M);
    int offset = 0;
    for (int i = 0; i < 5; i++) {
        mbf.put(msg.getBytes());// 写入 page cache, 有几率不刷盘
        offset += msg.length();
    }
    // 强制刷盘
    //mbf.force(); //jdk5
    //mbf.force(0, offset); //jdk13
}

private void zeroCopy() throws FileNotFoundException, IOException {
    var inputFileCh = new FileInputStream(LOG_FILE_PATH).getChannel();
    var outputFileCh =
            new FileOutputStream("/Users/xuzeng/Documents/usr/Java/private/AnatomyQuark/hack-jdk13/files/copyed.txt")
                    .getChannel();
    var buffer = ByteBuffer.allocateDirect(1024);
    while (inputFileCh.read(buffer) != -1) {
        buffer.flip(); // Prepare for writing——limit=postion;position=0;mark=-1;
        outputFileCh.write(buffer);
        buffer.clear();  // Prepare for reading——position=0;limit=capacity;mark=-1;
    }
}