使用持续时间的汇总时间

问题描述 投票:-1回答:1

对于我的项目,我必须读入以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);
            }
        }
    }
}

这应该返回

[[芝麻街|最好的Elmo | 0:28:11]

但返回

[最佳Elmo |芝麻街| ,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]

java duration inputmismatchexception
1个回答
0
投票

您可以考虑查找并使用第三方库来读取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。这并不完全是琐碎的事,但是已经有答案说明如何做到这一点。我在底部插入一个链接。使用Duration.plus(Duration)汇总持续时间。最后,您需要将总持续时间格式化回字符串以输出。我为此提供了另一个链接。

快乐编码。

链接

© www.soinside.com 2019 - 2024. All rights reserved.