2013-01-10 20 views
0

我想測試MappedByteBuffer的READ_WRITE模式。但我得到一個例外:使用MappedByteBuffer的READ_Write模式時發生異常

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

我不知道必須解決它。 在此先感謝。

現在我修好了程序,沒有例外。但是系統返回一系列垃圾字符,但實際上文件in.txt中只有一個字符串「asdfghjkl」。我想可能是編碼方案導致這個問題,但我不知道如何驗證並修復它。

import java.io.File; 
import java.nio.channels.*; 
import java.nio.MappedByteBuffer; 
import java.io.RandomAccessFile; 

class test{ 
    public static void main(String[] args) throws Exception{ 

    File f= new File("./in.txt"); 
    RandomAccessFile in = new RandomAccessFile(f, "rws"); 
    FileChannel fc = in.getChannel(); 
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, f.length()); 

    while(mbb.hasRemaining()) 
     System.out.print(mbb.getChar()); 
    fc.close(); 
    in.close(); 

    } 
}; 

回答

1

FileInputStream僅用於閱讀和你正在使用FileChannel.MapMode.READ_WRITE。它應該是READFileInputStream。使用RandomAccessFile raf = new RandomAccessFile(f, "rw");作爲READ_WRITE地圖。

編輯: 您的文件中的字符可能是8位,而java使用16位字符。因此getChar將讀取兩個字節而不是單個字節。

使用get()方法,並將其轉換爲char得到您想要的字符:

while(mbb.hasRemaining()) 
     System.out.print((char)mbb.get()); 

另外,因爲該文件可能是基於US-ASCII,您可以使用CharsetDecoder獲得CharBuffer,例如:

import java.io.*; 
import java.nio.*; 
import java.nio.channels.*; 
import java.nio.charset.*; 

public class TestFC { 
     public static void main(String a[]) throws IOException{ 
       File f = new File("in.txt"); 
       try(RandomAccessFile in = new RandomAccessFile(f, "rws"); FileChannel fc = in.getChannel();) { 
         MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, f.length()); 

         Charset charset = Charset.forName("US-ASCII"); 
         CharsetDecoder decoder = charset.newDecoder(); 
         CharBuffer cb = decoder.decode(mbb); 

         for(int i=0; i<cb.limit();i++) { 
           System.out.print(cb.get(i)); 
         } 
       } 
     } 
} 

也會給你想要的結果。

+0

@Charles Menguy感謝格式。你使用反引號來標記代碼嗎? –

+0

感謝您的幫助。現在我有另一個問題,請再次看到我的問題,我已經編輯它 – city

+0

@city回答更新。 –

1

Acc。到的Javadoc:

NonWritableChannelException - 如果模式是READ_WRITE或PRIVATE,但此通道未打開的讀取和寫入

的FileInputStream - 是指用於例如圖像的原始字節讀取流數據。

的RandomAccessFile - 這個類的實例支持讀取和寫入隨機訪問文件

在地方的FileInputStream,使用RandomAccessFile

相關問題