當使用文件流讀取文本文件時,如果遇到中文字符,將會讀到亂碼.
偶然的一次在一本參考書看到 用byte數(shù)組存儲讀取結果,再用byte數(shù)組構建字符串,可解決亂碼問題,試了一下,果然見效了,于是寫了下面一個簡單的類,以備用.
/**
* @(#)ReadText.java 17:59 10/09/06
* @versoin 0.01
* @author 林志斌(alvin) 廣東 普寧 里湖
* Copyright ? 1996-2006 zmzx.icpcn.com. All Rights Reserved
* Use is subject to license terms.
*/
package alvin.alvinio;
import java.io.File;
import java.io.FileInputStream;
public class ReadText {
public static String getText(String path) throws Exception {
FileInputStream in = new FileInputStream(path);
byte[] bit = new byte[in.available()];
in.read(bit);
in.close();
return (new String(bit));
}
//測試函數(shù)
public static void main(String[] a) throws Exception{
//從磁盤讀取文本文件并打印
String str = ReadText.getText("c:/hello.txt");
System.out.println(str);
}
}