public FileProcessor(String filenameIn, String fileModeIn){
try {
randomaccessfile = new RandomAccessFile(filenameIn, fileModeIn);
fileChannel = randomaccessfile.getChannel();
buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileChannel.size());
} catch (FileNotFoundException e) {
System.err.println("Error while creating a File");
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
System.err.println("Error while creating MappedByteBuffer");
e.printStackTrace();
System.exit(1);
}
获得
Exception in thread "main" java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:880)
答案 0 :(得分:2)
如果您在创建"rw"
时需要RandomAccessFile
映射文件时需要READ_WRITE,那么您最终会从中获取该文件。
答案 1 :(得分:0)
当fileModeIn
和FileChannel.MapMode.READ_WRITE
没有匹配时,我的小型可重现程序会出现错误。
示例程序:
import java.io.*;
import java.nio.channels.*;
import java.nio.MappedByteBuffer;
class SampleFileProcessor {
public static void main(String[] args) {
String fileName = args[0];
String mode = args[1];
JFP jf = new JFP();
jf.FileProcessor(fileName,mode);
}
public void FileProcessor(String filenameIn, String fileModeIn){
try {
RandomAccessFile randomaccessfile = new RandomAccessFile(filenameIn, fileModeIn);
FileChannel fileChannel = randomaccessfile.getChannel();
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileChannel.size());
} catch (FileNotFoundException e) {
System.err.println("Error while creating a File");
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
System.err.println("Error while creating MappedByteBuffer");
e.printStackTrace();
System.exit(1);
}
}
}
输入&输出:
echo "Non-matching fileModeIn and FileChannel.MapMode"
java SampleFileProcessor input_file.txt r
Exception in thread "main" java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:799)
at JFP.FileProcessor(JFP.java:19)
at JFP.main(JFP.java:9)
<Error>
echo "Matching fileModeIn and FileChannel.MapMode"
java SampleFileProcessor input_file.txt rw
<Success>