2015-07-10 133 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; 

}