2016-11-14 25 views
0
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); 
     } 

異常線程 「main」 java.nio.channels.NonWritableChannelException 在sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:880)JAVA - 非可寫通道異常

獲取NonwritableChannelException爲上面的代碼。請幫忙。謝謝。!!

+0

什麼是你的fileModeIn? – developer

+0

我得到一個文件模式作爲輸入,但默認設置爲READ_WRITE – ShreyasMN

回答

0

當我的最後一個小型可重複程序在fileModeInFileChannel.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> 
0

如果你想READ_WRITE映射文件,當您創建RandomAccessFile你最終從得到它時需要"rw" ..