从文本文件中一行的中间提取时间戳

Extract timestamp from the middle of a line in text file

我正在尝试读取一个包含不同信息的文本文件。文本文件的一部分包含我需要的以下信息

### Size: 280
### file data: 
### Scenario: - timestamp: 1620832134319 - Wed May 12 17:08:54 CEST 2021
### It needed to compare later timestamp: 1620832134319 - Wed May 12 17:08:54 CEST 2021

我正在尝试提取此时间戳“1620832134319”或“5 月 12 日星期三 17:08:54”。然后我需要在未来添加 10 天。比较原始时间戳和未来10天时间戳是否相同

在这种情况下,有人可以帮助我或指导我吗?到目前为止,我一直试图打开文件,但读取和提取时间戳并添加更多部分才是我真正遇到的问题。

public class readTimeStampTest
{

static String filePath = "c:/timestamp.txt";
long timestamp10daysinfuture = 1621868934;

public static void getTimeStamp()
{
    System.out.println("timestamp test... " );
    File file = new File(filePath);
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line;
    while((line = br.readLine()) != null){
        //process the line
        System.out.println(line);

   1st step:  Extract timestamp 

   2nd step: Compare original and future timestamp (timestamp10daysinfuture )


   }     }

我试图在 SO 中查找以首先提取时间戳,但是该时间戳的格式与下面 link 中提到的不同。因为通常时间戳在文本文件的开头,但在这里它在中间,我认为它需要正则表达式。

How to Read Time and Date from Text File in Java 5?

如有任何帮助,我们将不胜感激。

您可以使用正则表达式 (?<=timestamp:\h)\d+(?=\h-) 来检索匹配项。

与Java-11:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        return Pattern.compile("(?<=timestamp:\h)\d+(?=\h-)")
                    .matcher(Files.readString(Path.of(filePath), StandardCharsets.US_ASCII))
                    .results()
                    .map(MatchResult::group)
                    .findAny()
                    .orElse("");
    }
}

输出:

1620832134319

与Java-9:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        String str = Files.lines(Paths.get(filePath), StandardCharsets.US_ASCII).collect(Collectors.joining());
        return Pattern.compile("(?<=timestamp:\h)\d+(?=\h-)")
                    .matcher(str)
                    .results()
                    .map(MatchResult::group)
                    .findAny()
                    .orElse("");
    }
}

与Java-8:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        String str = Files.lines(Paths.get(filePath), StandardCharsets.US_ASCII).collect(Collectors.joining());
        Matcher matcher = Pattern.compile("(?<=timestamp:\h)\d+(?=\h-)").matcher(str);
        if (matcher.find()) {
            return matcher.group();
        } else {
            return "";
        }
    }
}

regex101处正则表达式的解释:

Positive Lookbehind (?<=timestamp:\h)
    Assert that the Regex below matches
    timestamp: matches the characters timestamp: literally (case sensitive)
    \h matches any horizontal whitespace character (equivalent to [[:blank:]])
\d matches a digit (equivalent to [0-9])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
Positive Lookahead (?=\h-)
    Assert that the Regex below matches
    \h matches any horizontal whitespace character (equivalent to [[:blank:]])
    - matches the character - literally (case sensitive)

如何处理检索到的时间戳的演示:

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws IOException {
        String timestamp = "1620832134319";

        // Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
        ZonedDateTime zdt = Instant.ofEpochMilli(Long.parseLong(timestamp)).atZone(ZoneId.systemDefault());
        System.out.println(zdt);

        zdt = zdt.plusDays(10);
        System.out.println(zdt);

        // Custom format
        System.out.println(DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH).format(zdt));
    }
}

输出:

2021-05-12T16:08:54.319+01:00[Europe/London]
2021-05-22T16:08:54.319+01:00[Europe/London]
05/22/2021