2016-10-21 9 views
0

私はTimeEntryBufferedReaderと以下を読んでみたいです。LocalDate with bufferedreader - java

Date: 11.10.2016 
start: 09:00 

私はLocalDateStringを変換する方法を知っているが、私は私がこの必要と思いますか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(); 
} 

答えて

1

どのようにこのような何かについては?あなたは `文字列#マッチ(正規表現)を呼び出すことは避けるべき

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 
} 
+0

は'ループ内では –

+0

@NicolasFilotto真のコストがかかり、各呼び出しで正規表現を再コンパイルされますよう。同じ理由から、コードはループ内に 'DateTimeFormatter'オブジェクトを作成すべきではありません。 - - あ、ちょっと待って。私のコードはループを持っていません。 – Andreas

+0

ああそうだね、ストリームやループなしで 'BufferedReader'を使用するのは珍しいことですが、私はそれを逃してしまいました。 –