我希望将TimeEntry
与BufferedReader
一起阅读以下内容。
Date: 11.10.2016
start: 09:00
我知道如何将String
转换为LocalDate
,但我不知道如何在BufferedReader
我想我需要这个:
Pattern p = Pattern.compile(
" * Date:*(\\\d\\\ d)\\\ .(\\\d\\\d)\\\ .(\\\d\\\d\\\d\\\d) *"
);
public class TimeEntry {
private LocalDate date;
private LocalTime start;
public TimeEntry(LocalDate date, LocalTime start) {
this.date = date;
this.start = start;
}
try {
File file = new File("MailDaten.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line = null;
String[] line_split = line.split(" ");
String test = line_split[0];
int s = test.split("@")[0].lastIndexOf(" ");
String name = test.substring(0,s);
String mail = test.substring(s+1,test.length());
while ((line = bufferedReader.readLine()) != null) {
line_split = line.split(" ");
Daten.add(
new MailEntry(
name, mail,
new TimeEntry(
line_split[3], line_split[3], line_split[4], line_split[5]
)
)
);
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:2)
这样的事情怎么样?
String input = "Date: 11.10.2016\r\n" +
"start: 09:00\r\n";
try (BufferedReader in = new BufferedReader(new StringReader(input))) {
String dateLine = in.readLine();
String startLine = in.readLine();
if (! dateLine.matches("Date: \\d{2}\\.\\d{2}\\.\\d{4}"))
throw new IllegalArgumentException("Invalid date line: " + dateLine);
if (! startLine.matches("start: \\d{2}:\\d{2}"))
throw new IllegalArgumentException("Invalid start line: " + startLine);
LocalDate date = LocalDate.parse(dateLine.substring(6), DateTimeFormatter.ofPattern("dd.MM.uuuu"));
LocalTime start = LocalTime.parse(startLine.substring(7), DateTimeFormatter.ofPattern("HH:mm"));
LocalDateTime dateStart = LocalDateTime.of(date, start);
System.out.println(dateStart); // prints: 2016-10-11T09:00
}