Java - 文本文件 - 在某些字符串之间读取

时间:2015-12-31 00:20:57

标签: java

我试着在过去的20个小时内弄清楚以下问题,所以在我开始考虑跳出窗外之前我想:-),我最好在这里寻求帮助:

I have a text file with following content:
ID
1
Title
Men and mice
Content
Lenny loves kittens
ID
2
Title
Here is now only the Title of a Book
ID
3
Content
Here is now only the Content of a Book

你可以看到的问题是id后面有标题和内容,id后面只有标题。 我想创建包含ID值(例如1)的文本文件以及相应的标题值和/或内容值。

我取得的最好成绩是三个名单。一个具有id值,一个具有标题值,另一个具有内容值。但实际上它没用,因为id,内容和标题之间的信息都会丢失。

我真的很感激你的举动。

2 个答案:

答案 0 :(得分:2)

所以你想要用三个字段填充一个类的集合。

class Data {
    int id;
    String title;
    String content;

    // helper method to read a file and return a list.
    public static List<Data> readAll(String filename) throws IOException {
        // List we will return.
        List<Data> ret = new ArrayList<Data>();
        // last value we added.
        Data last = null;
        // Open a file as text so we can read the lines.
        // us try-with-resource so the file is closed when we are done.
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            // declare a String and use it in a loop.
            // read line and stop when we get a null
            for (String line; (line = br.readLine()) != null; ) {
                // look the heading.
                switch (line) {
                    case "ID":
                        // assume ID is always first
                        ret.add(last = new Data());
                        // read the next line and parse it as an integer
                        last.id = Integer.parseInt(br.readLine());
                        break;

                    case "Title":
                        // read the next line and save it as a title
                        last.title = br.readLine();
                        break;
                    case "Content":
                        // read the next line and save it as a content
                        last.content = br.readLine();
                        break;
                }
            }
        }
        return ret;
    }
}

注意:唯一重要的字段是ID。内容和标题是可选的。

从20小时到5分钟,你需要练习很多。

答案 1 :(得分:1)

您可以保留ID,内容和标题之间的信息&#34;在你的程序中,如果你创建一个Book类,然后有一个Book实例列表。

图书课程:

abc

书籍清单:

public class Book {

    private int id;
    private String title;
    private String content;

    //...
    //getters and setters

}