簡體   English   中英

從文本文件中的一行中間提取時間戳

[英]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”或“Wed May 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 以首先提取時間戳,但該時間戳采用不同的格式,如下面的鏈接中所述。 因為通常時間戳在文本文件的開頭,但在這里它在中間,我認為它需要正則表達式。

如何從 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("");
    }
}

Output:

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));
    }
}

Output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM