0

I am trying to read one text file which contains different information. One part of the text file contains the below information that I needed

### 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

I am trying to extract this timestamp "1620832134319" or "Wed May 12 17:08:54". Then I need to add 10 days in the future. and compare the original timestamp and timestamp 10 days in the future more if they are the same or not.

Can someone please help me or guide me in this scenario. Until now I tried to open the file but reading and extracting that timestamp and adding more parts is where I am really stuck.

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 )


   }     }

I tried to look in SO for extracting the timestamp first, but that timestamp is in a different format as mentioned in the below link. because normally the timestamp is at the start of the text file, but here it is in middle and I think it needs regex.

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

Any help would be greatly appreciated.

rob
  • 153
  • 2
  • 6
  • 13
  • I think that you're right: a good option is to use a regular expression. If the timestamps have a "weird" format, you should take a few samples and create a regex for them :) Then, this post might be useful to you to transform the string into a timestamp object: https://stackoverflow.com/questions/18915075/java-convert-string-to-timestamp – dimasdmm Apr 26 '21 at 09:43
  • @dimasdmm yes, that where I am stuck. I am unable to extract timestamps from an above-mentioned text file. – rob Apr 26 '21 at 10:00
  • Does the line which contains the timestamp always include and start with `### Scenario: - timestamp:` ? Is it always on line 3 or could it be anywhere else? are there more than the two timestamps in the file? – Eritrean Apr 26 '21 at 10:27
  • @Eritrean yes it always contain this – rob Apr 26 '21 at 10:30

1 Answers1

5

You can use the regex, (?<=timestamp:\h)\d+(?=\h-) to retrive the match.

With 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

With 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("");
    }
}

With 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 "";
        }
    }
}

Explanation of the regex at 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)

A demo of how to process the retrieved timestamp:

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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • thanks for helping me. I am getting following error: "The method results() is undefined for the type Matcher" and "The method of(String) is undefined for the type Path" – rob Apr 26 '21 at 10:20
  • It's available from Java-9. Are you using a lower version of JDK? – Arvind Kumar Avinash Apr 26 '21 at 10:22
  • yes, i am using 1.8.0_202 cox this is required to use. – rob Apr 26 '21 at 10:28
  • 1
    @rob - Alright...now, I've posted an update for the Java-8 solution. I hope it solves your problem. – Arvind Kumar Avinash Apr 26 '21 at 10:29
  • Thanks for such a valuable input. the timestamp is stored in the string. thanks a lot again . Can you mention one more data. like to add 10 more future days in this timestamp which we obtained from this file. the rest of operations i can easily perform myself. – rob Apr 26 '21 at 10:49
  • 1
    @rob: Please avoid adding new requirements from comments. Question was about extracting timestamp from given input. – anubhava Apr 26 '21 at 10:51