无法读取日志文件并无法加载到db Java

时间:2018-12-06 14:19:43

标签: java jpa

我有一个包含此类数据的日志文件

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"

我有20多行,我想阅读每一行,首先得到一行,然后按管道分割|

所以我的想法是首先创建一个简单的bean,该bean可以将分离的数据用于他们的setter方法,以便可以将它们保存在db中。 但是我还没有能够准确读取第一行的

从我的代码中,您可以了解我想做什么。

      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

运行此命令我会得到

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

所以我通过使用system.out进行调试,发现它只读取整个日期中的2个,我在做什么错呢? 而且我希望它能够连续读取并存储在db中

将拆分更改为

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

因此,它现在至少读取日期的一半,但仍不完整 我该怎么办?

1 个答案:

答案 0 :(得分:1)

您需要使用特定的格式化程序:

logBean.setDateTime(
    LocalDateTime.parse(
        split[0],
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") // java.time.format.DateTimeFormatter
    )
);