为了账号安全,请及时绑定邮箱和手机立即绑定

我对 Java NIO 感到困惑

我对 Java NIO 感到困惑

慕桂英3389331 2022-07-20 16:49:43
我对 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 是在写入文件时中断线程还是作为非阻塞工作
查看完整描述

2 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

版本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 里面。


查看完整回答
反对 回复 2022-07-20
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

  1. Files.write(...)使用OutputStream而不是RandomAccessFile.getChannel(). 它有一些不同的机制,所以最好用谷歌搜索一下

  2. Files.write(...)写入文件的逻辑要短得多且封装性强

  3. 当你使用这样的“低”代码时,你需要照顾很多事情。例如,在您的示例中,您没有关闭频道。

因此,总而言之,如果您只需要编写 - 更好地使用Files或其他高级 API。如果您在读/写期间需要一些“附加”功能,您需要使用RandomAccessFileInputStream/OutputStream


查看完整回答
反对 回复 2022-07-20
  • 2 回答
  • 0 关注
  • 72 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号