gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:54:42 28 4
gpt4 key购买 nike

在过去的 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、content 和 title 之间的信息丢失了。

我非常感谢您的支持。

最佳答案

因此,您想用三个字段填充类的集合。

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 分钟,您需要大量练习。

关于Java - 文本文件 - 在某些字符串之间读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34539320/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com