我对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();
}