Java Nio 无法写入文件,老式文件有效。怎么了?



下面的 MWE 展示了我对如何使用 nio 编写文件的理解。 但是,打开文件时失败。 为了证明目录没有问题,在同一个项目、同一个目录中编写了一个老式文件。 蔚来代码有什么问题?

错误:线程"main"java.nio.file.NoSuchFileException:test.dat中的异常。 请注意,该选项设置为CREATE,它应该写入现有文件或创建新文件!

import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.channels.*;
public class FastWritenio {
    public static void writeUsingPrintWriter() throws IOException {
        PrintWriter pw = new PrintWriter(new FileWriter("test.txt"));
        pw.print("testing");
        pw.close();
    }
    public static void writeUsingnio(int numTrials, int bufferSize, int putsPer) throws IOException {
        String filename = "test.dat";
        java.nio.file.Path filePath = Paths.get(filename);
        WritableByteChannel channel = Files.newByteChannel(filePath, StandardOpenOption.CREATE);
        ByteBuffer buf = ByteBuffer.allocate(bufferSize);
        for (int t = 0; t < numTrials; ++t) {
            for (int i = 0; i < putsPer; i ++) {
                buf.putInt(i);
            }
            buf.flip(); // stop modifying buffer so it can be written to disk
            channel.write(buf);  // Write your buffer's data.
        }
        channel.close();
    }
    public static void main(String[] args) throws IOException {
        writeUsingPrintWriter();
        writeUsingnio(16, 8*1024, 1024);
    }
}

从文档中删除:

这两种newByteChannel方法都允许您指定 OpenOption 选项的列表。除了另一个选项外,还支持newOutputStream方法使用的相同打开选项:READ是必需的,因为SeekableByteChannel同时支持读取和写入。

指定READ将打开读取通道。指定WRITEAPPEND将打开写入通道。如果未指定这些选项,则打开通道进行读取。

你的OpenOptions不足。在您的示例中设置WritableByteChannel channel = Files.newByteChannel(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND);会在 Windows 上创建文件,但最终会出现 BufferOverflow

相关内容

最新更新