【问题标题】:Unable to read a log file and loading to db java [duplicate]无法读取日志文件并加载到 db java [重复]
【发布时间】:2019-05-08 06:28:26
【问题描述】:

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

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,它可以在它们的 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 个,我做错了什么? 我希望它能够持续读取并存储在数据库中

将拆分改为

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

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

【问题讨论】:

  • 您的 split[0] 文本不是正确的模式日期时间字符串,应该是这样的模式:2011-12-03T10:15:30
  • 你的意思是@Liuguanghua DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") ?我试过了,但结果相同,我会更新我的问题以包括那个
  • 哦,我完全错过了那个管道。
  • 嗯,是的,我正在从文件中读取,因为你看到我发布了文件的一部分
  • @BackSlash 这个问题和那个不同

标签: java jpa


【解决方案1】:

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

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

【讨论】:

  • 我这样做了,然后运行我的主要方法来获取日期,它仍然显示相同的答案 DateTimeParseException Text 2 could not be pared
  • @valik 那么您没有解析您发布的日期之一。检查demo,它适用于提供的输入。
  • 是的,可能我的问题是如何读取文件并通过管道拆分它们并使用setter方法获取它们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多