猿问

我对 Java NIO 感到困惑

我对 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 是在写入文件时中断线程还是作为非阻塞工作


慕桂英3389331
浏览 73回答 2
2回答

人到中年有点甜

版本Files更短更容易理解。其他版本更灵活。当您只有一个要写入的文件时,它不是很有用,但如果您在不同的存储中有许多文件,它可以为您节省一些资源。编辑这是Files.write源代码:public static Path write(Path path, byte[] bytes, OpenOption... options)    throws IOException{    // ensure bytes is not null before opening file    Objects.requireNonNull(bytes);    try (OutputStream out = Files.newOutputStream(path, options)) {        int len = bytes.length;        int rem = len;        while (rem > 0) {            int n = Math.min(rem, BUFFER_SIZE);            out.write(bytes, (len-rem), n);            rem -= n;        }    }    return path;}如您所见,它内部没有使用 NIO,只有 good old OutputStream。编辑 2事实上Files.newOutputStream不要FileOutputStream像我预期的那样回来。它返回OutputStream定义在Channels.newOutputStream哪个使用 NIO 里面。

小唯快跑啊

Files.write(...)使用OutputStream而不是RandomAccessFile.getChannel(). 它有一些不同的机制,所以最好用谷歌搜索一下Files.write(...)写入文件的逻辑要短得多且封装性强当你使用这样的“低”代码时,你需要照顾很多事情。例如,在您的示例中,您没有关闭频道。因此,总而言之,如果您只需要编写 - 更好地使用Files或其他高级 API。如果您在读/写期间需要一些“附加”功能,您需要使用RandomAccessFile或InputStream/OutputStream
随时随地看视频慕课网APP

相关分类

Java
我要回答