逐行读取文本文件并放入对象数组

时间:2015-07-10 21:07:10

标签: java arrays file text line

我必须使用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 个答案:

答案 0 :(得分:3)

readLine()只读取一行,所以你需要循环它,如你所说。 但是读取while循环中的String后,总是会覆盖该String。 您需要在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 :(得分:1)

使用apache commons lib

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

答案 2 :(得分: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;

}

相关问题