1.通過ByteBuffer的get()方法每次讀取一個字節轉換成char類型輸出.
fc = new FileInputStream("src/demo20/data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); buff = ByteBuffer.allocateDirect(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { System.out.print((char)buff.get()); }
2.使用系統字符集進行解碼
FileChannel fc = new FileOutputStream("src/demo20/data2.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text".getBytes())); buff.rewind(); String encoding = System.getProperty("file.encoding");//獲取系統字符集 System.out.println("Decoded using "+ encoding + ":" + Charset.forName(encoding).decode(buff));//Decoded using GBK:Some text
System.getProperty可以獲取系統字符集,可以用產生系統字符集的CharSet對象,來進行解碼操作.
3.寫入時進行編碼
fc = new FileOutputStream("src/demo20/data2.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE"))); fc.close(); fc = new FileInputStream("src/demo20/data2.txt").getChannel(); buff.clear(); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer());
ByteBuffer.wrap()方法將 ""UTF-16BE"編碼的 byte 數組包裝到緩沖區中,寫入文件,轉換成CharBuffer即可讀取文件.
4.通過CharBuffer寫入
fc = new FileOutputStream("src/demo20/data2.txt").getChannel(); buff = ByteBuffer.allocate(24); buff.asCharBuffer().put("Some text"); fc.write(buff); fc.close(); fc = new FileInputStream("src/demo20/data2.txt").getChannel(); buff.clear(); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer());
buff分配了24個字節,能儲存12個字符,寫入Some text可以通過FileInputStream獲取的通道讀取.