Posted on 2011-08-15 00:42
java小爬蟲 閱讀(373)
評論(0) 編輯 收藏
讀取文件的時候,要指定文件輸入
流的編碼格式。否則讀取的中文文件就是亂碼。
.txt unicode
.java 可以指定編碼格式
.xml 有成熟的讀寫工具
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FileTest {
static String fileName = "d:\\word.txt";
public static void main(String[] args) throws Exception {
System.out.println(readFile(fileName));
}
public static String readFile(String filePathAndName) {
String fileContent = "";
try {
File f = new File(filePathAndName);
if (f.isFile() && f.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(f), "unicode");
BufferedReader reader = new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null) {
fileContent += line;
}
read.close();
}
} catch (Exception e) {
System.out.println("讀取文件內容操作出錯");
e.printStackTrace();
}
return fileContent;
}
}