作者:Flyingis
JDK1.4開始便引入了java.nio.*包,其目的在于提高I/O的速度,這是因為該類庫使用的結構更接近于操作系統執行I/O的方式,即通過通道和緩沖器來讀寫數據。在實際應用中,和我們直接交互的是緩沖器,然后把緩沖器派送到通道,通道要么從緩沖器獲得數據,要么向緩沖器發送數據。
在基于Java的各種開發中,字符編碼是常見的問題之一,在最基本的Java I/O中也存在這種問題。新的Java I/O通過通道和緩沖器來讀寫數據,緩沖器容納的是普通的字節,為了把它們轉換成字符,我們要么在輸入的時候對其進行編碼,要么在從緩沖器輸出時對它們進行解碼。
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class ByteToCharacter {
private static final int SIZE = 1024;
public static void main(String[] args) throws Exception {
FileChannel fc = new FileOutputStream(“Output.txt”).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(SIZE);
/**
* 在輸入的時候進行編碼方式一
*/
fc.write(ByteBuffer.wrap(“Good holiday!”.getBytes(“UTF-16BE”))); // UTF-16BE可以更換為其他編碼方式
fc.close();
fc = new FileInputStream(“Output.txt”).getChannel();
fc.read(buffer);
buffer.flip(); //準備從緩沖區讀取已經寫入的數據
System.out.println(buffer.asCharBuffer());
/**
* 在輸入的時候進行編碼方式二
* 通過asCharBuffer()方法直接以char形式將字符寫入
*/
fc = new FileOutputStream(“Output.txt”).getChannel();
buffer.clear();
buffer.asCharBuffer.put(“Good holiday has passed!”);
fc.write(buffer);
fc.close();
fc = new FileInputStream(“Output.txt”).getChannel();
buffer.clear();
fc.read(buffer);
buffer.flip();
System.out.println(buffer.asCharBuffer());
/**
* 從緩沖器輸出時進行編碼
*/
fc = new FileOutputStream(“Output.txt”).getChannel();
fc.write(ByteBuffer.wrap(“Once again!”.getBytes()));
fc.close();
fc = new FileInputStream(“Output.txt”).getChannel();
buffer.clear();
fc.read(buffer);
buffer.flip();
String encode = System.getProperty(“file.encoding”); // 平臺缺省字符集,更加通用的方法,跨平臺特性的體現之一
System.out.println(Charset.forName(encode).decode(buffer));
}
}
在上述代碼中,如果不對從緩沖器寫入的數據進行正確編碼,那么當再次通過緩沖器讀取這些數據時,將不能顯示任何所需要的數據。
JDK中的java.nio.charset.Charset類提供了把數據編碼成多種不同類型的字符集的工具,滿足在各種應用中的編碼需求。