1

I have a log file with data as such

2017-01-01 00:00:11.763|192.168.234.82|"GET / HTTP/1.1"|200|"swcd (unknown version) CFNetwork/808.2.16 Darwin/15.6.0"

2017-01-01 00:00:21.164|192.168.234.82|"GET / HTTP/1.1"|200|"swcd (unknown version) CFNetwork/808.2.16 Darwin/15.6.0"

I have over 20 lines i want to read each line and first get a line and split by pipe |

so my idea was first to create a simple bean that can take the seperated data in their setter methods so i can save them in db But i have not bean able to accurately read the first line

From my code you could get the idea of what i want to do.

      public static LogBean readFile() throws IOException {

                Scanner read = new Scanner(new File("/resources/access.txt"));

                LogBean logBean = new LogBean();

                String string =  read.nextLine();
                Scanner readFileByLine = new Scanner(string);

                while (readFileByLine.hasNext()) {
                    String[] split = readFileByLine.next().split("|");
                    System.out.println(split[0]); // returns 2

  logBean.setDateTime(LocalDateTime.parse(split[0],
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") // java.time.format.DateTimeFormatter
            ));
                    logBean.setIp_address(split[1]);
                    logBean.setRequest(split[2]);
                    logBean.setStatus(split[3]);
                    logBean.setUserAgent(split[4]);
                }

                return logBean;

    I want to use jpa here to do logBeanRepository.save(logbean)
    in a continuous manner

when i run this i get

Exception in thread "main" java.time.format.DateTimeParseException: Text '2' could not be parsed at index 0

so i debugged by using system.out and saw that it just reads 2 out of the whole date , what am i doing wrong? and i would like it to continuously read and store in db

After changing the split to

    String[] split = readFileByLine.next().split("\\|");
Exception in thread "main" java.time.format.DateTimeParseException: Text '2017-01-01' could not be parsed at index 10

so now it reads at least half of the date but still not complete what can i do ?

valik
  • 2,014
  • 4
  • 24
  • 55

1 Answers1

1

You need to use a specific formatter:

logBean.setDateTime(
    LocalDateTime.parse(
        split[0],
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") // java.time.format.DateTimeFormatter
    )
);
BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • I did that then ran my main method to get date and it still shows thesame answer DateTimeParseException Text 2 could not be pared – valik Dec 06 '18 at 14:32
  • @valik Then you are not parsing one of the dates you posted. Check the [demo](https://ideone.com/38kzzB), it works with the provided input. – BackSlash Dec 06 '18 at 14:34
  • yes probably my issue is how to read the file and split them by pipe and also get them using setter method – valik Dec 06 '18 at 14:36