Skip to content

Read a time from file in java [closed]

I am doing a work for the university and I have to read many lines from file a with that format:

3ld4R7 4:27 3475

Everything is correct, each line represents a song, the first string is the name, the second the duration and the third the popularity. However, I don’t know exactly what type I can choose for the time. Then, I have to do many operations with the time (minutes, seconds, hours). I don’t know if there is a class in Java libraries for that such as Time or something like that. Any help is thanked!!!

Answer

java.time.Duration

The Duration class of java.time, the modern Java date and time API, is the class for — well, the name says it already. Unfortunately parsing a string like 4:27 into a Duration is not built-in. My preferred trick is:

    String durationString = "4:27";
    
    String isoString = durationString.replaceFirst("^(\d+):(\d+)$", "PT$1M$2S");
    Duration dur = Duration.parse(isoString);
    
    System.out.println(dur);

Output:

PT4M27S

Read as a period of time of 4 minutes 27 seconds. The Duration.parse method requires a format known as ISO 8601, an international standard. And Duration.toString(), implicitly called when we print the Duration, produces ISO 8601 back. It goes like what you saw, PT4M27S. So in my code, the first thing I do is convert your input from the file to ISO 8601 format, which I then parse.

If you want to format the duration for display, for example back in the same format as in the file:

    System.out.format("%d:%02d%n", dur.toMinutes(), dur.toSecondsPart());

4:27

Links