簡體   English   中英

使用bufferedReader讀取LocalDate-Java

[英]read LocalDate with bufferedreader - java

我想使用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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM