2015-07-10 135 views
2

我必須使用java製作EPG應用程序,但是我在編程方面有點新,而且它在明天到期,它仍然無法正常工作。逐行讀取文本文件並放入對象數組

我有一個小問題:我必須從文本文件中讀取程序。每行包含多個內容,頻道,節目標題,副標題,分類等等。

我必須確保我可以讀取每行的單獨部分,但它並不真正起作用,它只是從第一行打印部件。

我在嘗試,但我找不到它爲什麼不是從所有行中打印所有部件,而是僅打印第一行的部件。這裏是代碼:

BufferedReader reader = new BufferedReader(newFileReader(filepath)); 

while (true) { 
String line = reader.readLine(); 
    if (line == null) { 
     break; 
    } 
} 

String[] parts = line.split("\\|", -1); 
for(int i = 0; i < parts.length; i++) { 
System.out.println(parts[i]); 

} 
reader.close(); 

有沒有人知道如何獲得所有的行而不是隻有第一個?

謝謝!

+3

你錯過了一個關閉br高手;你的while語句實際上在哪裏結束? – azurefrog

+0

@azurefrog我相信撐杆只是爲了休息。我已經提出了一個編輯。 – Maxr1998

+0

@ Maxr1998這是一個合理的猜測,但仍然只是一個猜測。鑑於缺乏縮進,在OP澄清代碼之前,很難確定。 – azurefrog

回答

3

readLine()只讀取一行,所以你需要循環它,就像你說的那樣。 但讀取到while循環內的字符串,你總是覆蓋該字符串。 您需要在while循環之上聲明String,並且您可以從外部訪問它。

順便說一句,似乎你的牙套如果不匹配。

無論如何,我會填補信息到一個ArrayList,看看下面:

List<String> list = new ArrayList<>(); 
String content; 

// readLine() and close() may throw errors, so they require you to catch it… 
try { 
    while ((content = reader.readLine()) != null) { 
     list.add(content); 
    } 
    reader.close(); 
} catch (IOException e) { 
    // This just prints the error log to the console if something goes wrong 
    e.printStackTrace(); 
} 

// Now proceed with your list, e.g. retrieve first item and split 
String[] parts = list.get(0).split("\\|", -1); 

// You can simplify the for loop like this, 
// you call this for each: 
for (String s : parts) { 
    System.out.println(s); 
} 
1

使用Apache公地的lib

 File file = new File("test.txt"); 
     List<String> lines = FileUtils.readLines(file); 
+1

對他的特殊情況來說這不是一種過度的殺傷力嗎?另外,他是編程新手,所以他不會/不應該使用libs。 – Maxr1998

+0

好的,也許我以前的代碼太過分了。我相信,展示替代方案是一種好方法。 –

+0

但他仍然不得不使用lib。無論如何,+1爲其他方法。 – Maxr1998

0

由於ArrayList中是動態的,嘗試,

private static List<String> readFile(String filepath) { 
String line = null; 
List<String> list = new ArrayList<String>(); 
try { 
    BufferedReader reader = new BufferedReader(new FileReader(filepath)); 
    while((line = reader.readLine()) != null){ 
     list.add(line); 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
return list; 

}