gpt4 book ai didi

java - 使用 bufferedreader 读取 LocalDate - java

转载 作者:行者123 更新时间:2023-12-02 03:16:48 26 4
gpt4 key购买 nike

我想使用 BufferedReader 将以下内容读入 TimeEntry

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();
}

最佳答案

像这样怎么样?

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
}

关于java - 使用 bufferedreader 读取 LocalDate - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40183003/

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