範例

public static void main( String[] args ) {
// 假設為預設字集 ISO-8859-1,且檔案含有 UTF-16BE 內容
FileReader fileReader = null;
try {
fileReader = new java.io.FileReader( "file1" ); //$NON-NLS-1$
System.out.println( fileReader.read() );
} catch ( IOException e ) {
e.printStackTrace();
}
}



解決方案
若要自行指定字元編碼值,請在 FileInputStream 上建構含有 CharsetDecoder 的 InputStreamReader。

public static void main( String[] args ) {
// 假設為預設字集 ISO-8859-1,且檔案含有 UTF-16BE 內容
InputStreamReader reader = null;
try {
reader = new InputStreamReader( new FileInputStream("file1"), "UTF-16BE");
System.out.println( reader.read() );
} catch ( IOException e ) {
e.printStackTrace();
}

}