java nio 无法写入文件,旧式文件可以工作。怎么了?`

标签 java file nio

下面的MWE展示了我对如何使用nio编写文件的理解。但是打开文件失败。为了证明该目录没有任何问题,在同一项目、同一目录中写入了一个老式文件。 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);
    }
}

最佳答案

引自documentation :

Both newByteChannel methods enable you to specify a list of OpenOption options. The same open options used by the newOutputStream methods are supported, in addition to one more option: READ is required because the SeekableByteChannel supports both reading and writing.

Specifying READ opens the channel for reading. Specifying WRITE or APPEND opens the channel for writing. If none of these options is specified, the channel is opened for reading.

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

关于java nio 无法写入文件,旧式文件可以工作。怎么了?`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47140174/

相关文章:

java - 接口(interface)内的 toString、hashcode 和 equals 方法

Java 默认访问级别(包私有(private)访问)。为什么用它?

java - 关闭非阻塞套接字 channel

java - 避免tomcat/spring-boot中慢客户端导致的线程饥饿

java - Hibernate envers 一对一的关系没有双方审核

java - java中如何分割下面的字符串?

file - Powershell:键入哈希文字错误后缺少 '='运算符

c - 如何在 c 中处理此类消息 - 'objectFromFile' 的类型冲突

c++ - 正确覆盖文件元素时出现问题(数字)

java - 我可以简化从二进制数据中读取简短内容吗