使用持续时间总结时间

Summing up times using Duration

对于我的项目,我必须读入 CSV 文件中提供给我们的数据并以特定格式写出。我几乎完成了,但我遇到的问题是我的程序没有完全阅读给定的时间。从这里开始,我的程序只是在读取所有给我的时间。

我试图将 String time 转换为整数,但它给了我一个 InputMismatchException

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.time.Duration;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;

    public class MusicInventory {

    public long toHoursPart(Duration d) {
        return d.toHours() / 3600;
    }

    public long toMinutesPart(Duration d) {
        return d.toMinutes() % 60;
    }

    public long toSecondsPart(Duration d) {
        return d.toMillis() / 1000 % 60;

    }

    public static void process(File input, File output) throws FileNotFoundException {
        //read file
        List<String> inList = new ArrayList<>();
        try(Scanner scan = new Scanner(input)) {
            while(scan.hasNext()){
                String line = scan.nextLine();
                inList.add(line);
            }
        }



      //process data
        List<String> outList = new ArrayList<>();
        for (String now : inList) {
            try (Scanner scan = new Scanner(now)){
                scan.useDelimiter(",");
                String name = scan.next();
                String album = scan.next();
                String time = scan.nextLine();





                String next = String.format("%s | %s | %s ", name, album, time);
                outList.add(next);

            }
        }
      //write file
        try (PrintWriter pw = new PrintWriter(output)){
            for (String s : outList) {
                pw.println(s);
            }
        }
    }
}

这应该return

[Sesame Street | Best of Elmo | 0:28:11]

但是 returns

[Best of Elmo | Sesame Street | ,2:29,1:30,2:09,1:46,1:55,2:02,1:42,2:40,1:56,1:30,2:03,1:14,2:28,2:47]

您可以考虑查找并使用 third-party 库来读取您的 CSV 文件。有一些,还有一些可以免费使用。

我假设您的 CSV 文件中的一行如下所示:

Best of Elmo,Sesame Street,2:29,1:30,2:09,1:46,1:55,2:02,1:42,2:40,1:56,1:30,2:03,1:14,2:28,2:47

也就是说,该行中没有引号,名称或专辑标题中也没有逗号。在这种情况下,按照您尝试的方式使用 Scanner 读取和解析文件应该是易于管理的。要扫描时间,请使用内部循环,Scanner.hasNext()Scanner.next()(而不是 Scanner.nextLine())。每次从 Scanner.next() 解析为 Duration。这并非完全微不足道,但已经有解释如何做到这一点的答案。我在底部插入一个 link。使用 Duration.plus(Duration) 来总结持续时间。最后,您需要将总持续时间格式化回字符串以供输出。我为此添加了另一个 link。

链接