我对 java nio 缓冲区感到困惑,Files.write如果我可以在文件中写入缓冲区和通道,为什么我需要 Files 类。
这两个工作代码示例有什么区别。
String newData = "New String to write to file..." + System.currentTimeMillis();
Path path = Paths.get("C://data/nio-data2.txt");
try {
Files.write(path,newData.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
和
try {
RandomAccessFile aFile = new RandomAccessFile("C://data/nio-data.txt", "rw");
FileChannel channel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
channel.write(buf);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
编辑
我想再问一个问题,Channels.newOutputStream 是在写入文件时中断线程还是作为非阻塞工作
人到中年有点甜
小唯快跑啊
相关分类