问题描述
我想读取文件,并将每个条目添加到日期的arraylist中。但是日期也应该包括在内。
文件示例:
2002年9月15日,您好,这是第一个条目。
\ t这行,我也需要在第一行中输入。
\ t这行,我也需要在第一行中输入。
\ t这行,我也需要在第一行。
2020年10月17日这是下一个条目
我尝试了这个。但是读者只会读取第一行
public class versuch1 {
public static void main(String[] args) {
ArrayList<String> liste = new ArrayList<String>();
String lastLine = "";
String str_all = "";
String currLine = "";
try {
FileReader fstream = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fstream);
while ((currLine = br.readLine()) != null) {
Pattern p = Pattern
.compile("[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2} [0-2]?[0-9]:[0-6]?[0-9]:[0-5]");
Matcher m = p.matcher(currLine);
if (m.find() == true) {
lastLine = currLine;
liste.add(lastLine);
} else if (m.find() == false) {
str_all = currLine + " " + lastLine;
liste.set((liste.indexOf(currLine)),str_all);
}
}
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.print(liste.get(0) + " "+liste.get(1);
}
}
解决方法
我已经解决了我的问题:)
public class versuch1 {
public static void main(String[] args) {
ArrayList<String> liste = new ArrayList<String>();
String lastLine = "";
String currLine = "";
String str_all = "";
try {
FileReader fstream = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fstream);
currLine = br.readLine();
while (currLine != null) {
Pattern p = Pattern
.compile("[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2} [0-2]?[0-9]:[0-6]?[0-9]:[0-5]");
Matcher m = p.matcher(currLine);
if (m.find() == true) {
liste.add(currLine);
lastLine = currLine;
} else if (m.find() == false) {
liste.set((liste.size() - 1),(str_all));
lastLine = str_all;
}
currLine = br.readLine();
str_all = lastLine + currLine;
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.print(liste.get(1) + " ");
}
}
,在阅读这些行时,请保留一个“当前条目”。
如果读取的行以日期开头,则它属于新条目。在这种情况下,将当前条目添加到条目列表中,并创建一个由读取行组成的新当前条目。
如果该行不是以日期开头,则将其添加到当前条目中。
为此,您需要在循环之前将第一行读入当前条目。循环之后,您需要将当前条目添加到条目列表中。反过来,这仅在至少有一行并且第一行以日期开头时才有效。因此,请特别处理无行的特殊情况(使用if-else)。如果第一行不是以日期开头,则报告错误。
快乐的编码。