Search code examples
javafileexceptionnio

JAVA - Non Writable Channel Exception


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);
} 

Getting

Exception in thread "main" java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:880)

Solution

  • If you want READ_WRITE when mapping the file you need "rw" when creating the RandomAccessFile you are ultimately getting it from..