好久沒寫東西了,最近太忙了。今天做文件的操作發現點有趣的現象。放上來跟大家分享一下。
今天用IDEA做程序的本地文件的部分時,碰到一點小問題。程序如下:
1 package example;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileNotFoundException;
6 import java.io.FileReader;
7 import java.io.IOException;
8
9
10
11 public class FileOperation {
12
13 /**
14 * @param args
15 */
16 public static void main(String[] args) {
17 // TODO Auto-generated method stub
18 FileOperation fo = new FileOperation();
19 String s = "";
20 try {
21 s = fo.bufferedReaderDemo("D:/Project/IntelliJ/BrowseVisual/Resource/res/fo1.txt");
22 } catch (IOException e) {
23 // TODO Auto-generated catch block
24 e.printStackTrace();
25 }
26
27 System.out.println(s);
28
29 }
30
31 public String bufferedReaderDemo(String filename) throws IOException {
32 File file = new File(filename);
33 if (!file.exists() || file.isDirectory()) {
34 throw new FileNotFoundException();
35 }
36 BufferedReader br = new BufferedReader(new FileReader(file));
37 String temp;
38 StringBuffer sb = new StringBuffer();
39 temp = br.readLine();
40 while (temp != null) {
41 sb.append(temp).append(" ");
42 temp = br.readLine();
43 }
44 System.out.println(sb.length());
45
46 return sb.toString();
47 }
48
49 }
程序運行,IDEA輸出空白,整個IDEA近乎進入假死狀態。哪兒出問題了呢?經過排查否定了String和StringBuffer的問題,后來查看fo1.txt的文件格式居然是utf-8,難道跟這個有關系?經過測試,當fo1.txt只有10幾K的情況下,沒有問題,輸出亂碼,而當fo1.txt達到幾十K的時候,IDEA就沒法正常輸出了,當fo1.txt文件格式改為gbk的話,文件1M照樣正常運行。后又拿Eclipse測試,fo1.txt在utf-8下1M大小正常輸出亂碼(不過感覺好慢,除了IDEA那個假死狀態,程序在正常運行情況下,感覺Eclipse比IDEA慢上不少,有點難以忍受了)。
嗯。寫這個出來,只是想大家探討探討這到底是什么問題呢?為啥IDEA會出現這種狀況呢?馬上去NetBeans里測試測試。