2011-07-07 70 views
0
public static String[] words = null; 

public static String readFile(String name) { 
    int i = 0; 
    try { 
     BufferedReader br = new BufferedReader(new FileReader(name)); 
     try { 
      StringBuilder sb = new StringBuilder(); 
      String line = br.readLine(); 

      while (line != null) { 
       i++; 
       sb.append(sb.toString()); 
       sb.append("\n"); 
       line = br.readLine(); 
      } 
      String everything = sb.toString(); 
      words = everything.split("\\n");//not sure if this is right... 
     } finally { 
      br.close(); 
     } 
    } catch (Exception e) { 
     e.getMessage(); 
    } 
    return "Loaded " + i + " words"; 
} 

我基本上試圖讀取每行數據的文件。在文件中的每一行我試圖插入到數組中。願有人幫我弄清楚我在這裏做錯了什麼?讀取文件並將數據插入字符串[]

回答

7

的問題是:

while (line != null) { 
      i++; 
      sb.append(sb.toString()); 
      sb.append("\n"); 
      line = br.readLine(); 
     } 

某人實際上從來不附加任何東西,它只是一遍又一遍追加空字符串。

應該是:

while (line != null) { 
      i++; 
      sb.append(line); 
      sb.append("\n"); 
      line = br.readLine(); 
     } 
+0

得益於敏銳的眼睛:) – Kyle

+0

@Kyle不客氣。 –

相關問題