下面的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 thenewOutputStream
methods are supported, in addition to one more option:READ
is required because theSeekableByteChannel
supports both reading and writing.Specifying
READ
opens the channel for reading. SpecifyingWRITE
orAPPEND
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/