這兩種改法究竟有什麼區別呢?為了方便大家閱讀,我先把正確和錯誤的改法帖出來:
import java.io.*;
public class TestCodeIO {
public static void main(String[] args) throws Exception{
InputStreamReader isr = new InputStreamReader(System.in,"iso8859-1");
//Create an InputStreamReader that uses the given charset decoder
BufferedReader br = new BufferedReader (isr);
String strLine = br.readLine();
br.close();
isr.close();
System.out.println(strLine);
System.out.println(new String (strLine.getBytes(),"iso8859-1"));//錯誤改法
//Encodes this String (strLine) into a sequence of bytes using the platform’s
//default charset(gb2312) then constructs a new String by decoding the
//specified array of bytes using the specified charset (iso8859-1)
//because this String (strLine) uses the charset decoder "iso8859-1",so it can
//only be encoded by "iso8859-1",cann’t be encoded by the platform’s default
//charset "gb2312",so this line is wrong.
System.out.println(new String (strLine.getBytes("iso8859-1")));//正確改法
//Encodes this String (strLine) into a sequence of bytes using the named
//charset (iso8859-1),then constructs a new String by decoding the
//specified array of bytes using the platform’s default charset (gb2312).
//This line is right.
}
}