猿问

从 Java 中以逗号和标题分隔的文件中的读取时间

我有一个列表,文件中有很多次。我的目标是将所有时间都放在他们自己的名为time1,time2和的字符串数组中time3。该文件如下所示:


time1, 5:01,3:21,4:05,1:52 time2, 2:11,6:35,2:00,5:00 time3, 12:09, 

11:35, 9:02

我尝试将我读入的每一行拆分,然后将其转换为用逗号分隔的记号。但是,目前这似乎不是一个有效的解决方案,因为第一个元素总是以空格开头,而最后一个元素没有逗号。我想知道是否有人知道解决此问题的方法。


这是我到目前为止想出的代码:


public void read_file(){

try{

    times = new Scanner(new File("times.csv"));

    read_file();

}

catch(Exception e){

    System.out.printf("Could not find file\n");

}                

}

public void read_file(){


while(times.hasNextLine()){

    i++;

    String a = times.nextLine();

    String time[] = a.split(",");

    //would only add first 4 elements

    if(i < 4){

        timeList1.add(time[i])

    }

}

}

这里的问题是我不知道如何检查有多少元素我必须继续,因为列表中的次数是不可预测的。唯一保持不变的是,总会有 3 个时间列表,称为time1,time2和time3。


收到一只叮咚
浏览 165回答 3
3回答

杨魅力

这是另一种更简单的方法:public class ReadTimes {&nbsp; &nbsp; private Map<String, List<String>> timeLists = new HashMap();&nbsp; &nbsp; public void read_file() {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Scanner times = new Scanner(new File("times.csv"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; read_file(times);&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("Could not find file\n");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void read_file(Scanner times) {&nbsp; &nbsp; &nbsp; &nbsp; String label=null;&nbsp; &nbsp; &nbsp; &nbsp; while (times.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String time[] = times.nextLine().trim().split("[, ]+");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (String timeString : time) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (timeString.startsWith("time")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label = timeString;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeLists.put(label, new ArrayList());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else if (label != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeLists.get(label).add(timeString);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // dump the map of arraylists for demonstration purposes...&nbsp; &nbsp; &nbsp; &nbsp; for (Entry<String,List<String>> timeEntry : timeLists.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(timeEntry);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; ReadTimes rt = new ReadTimes();&nbsp; &nbsp; &nbsp; &nbsp; rt.read_file();&nbsp; &nbsp; }}鉴于您的问题中显示的输入数据,将产生以下输出:time1=[5:01, 3:21, 4:05, 1:52]time2=[2:11, 6:35, 2:00, 5:00]time3=[12:09, 11:35, 9:02]

米脂

由于您确定您只需要 3 个字符串数组,因此下面的代码使用“时间”作为分隔符拆分初始字符串,在开头删除"1, ", "2, ","3, "在,结尾处进行修剪和删除,最后在删除所有空格后将每个项目拆分为, 作为产生 3 个字符串数组的分隔符。&nbsp; &nbsp; String times = "time1, 5:01,3:21,4:05,1:52, time2, 2:11,6:35,2:00,5:00, time3, 12:09,11:35, 9:02";&nbsp; &nbsp; String[] splitted = times.split("time");&nbsp; &nbsp; // exclude 0th item which is ""&nbsp; &nbsp; for (int i = 1; i < splitted.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; splitted[i] = splitted[i].trim();&nbsp; &nbsp; &nbsp; &nbsp; int index = splitted[i].indexOf(" ");&nbsp; &nbsp; &nbsp; &nbsp; if (splitted[i].endsWith(","))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; splitted[i] = splitted[i].substring(index + 1, splitted[i].length() - 1);&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; splitted[i] = splitted[i].substring(index + 1);&nbsp; &nbsp; &nbsp; &nbsp; splitted[i] = splitted[i].replaceAll(" ", "");&nbsp; &nbsp; }&nbsp; &nbsp; try {&nbsp; // just in case&nbsp; &nbsp; &nbsp; &nbsp; String time1[] = splitted[1].split(",");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Arrays.toString(time1));&nbsp; &nbsp; &nbsp; &nbsp; String time2[] = splitted[2].split(",");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Arrays.toString(time2));&nbsp; &nbsp; &nbsp; &nbsp; String time3[] = splitted[3].split(",");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Arrays.toString(time3));&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }打印 3 个字符串数组:[5:01, 3:21, 4:05, 1:52][2:11, 6:35, 2:00, 5:00][12:09, 11:35, 9:02]

眼眸繁星

这是一个单元测试,它可以满足您的需求。我不得不稍微格式化您的输入字符串。您应该能够以最少的更改为您完成这项工作。import org.junit.Test;import java.time.LocalDate;import java.time.LocalTime;import java.time.format.DateTimeFormatter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/**&nbsp;* @author Dr. Parameter&nbsp;*/public class TimeParser {&nbsp; &nbsp; private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("k:mm");&nbsp; &nbsp; @Test&nbsp; &nbsp; public void test(){&nbsp; &nbsp; &nbsp; &nbsp; // Test input&nbsp; &nbsp; &nbsp; &nbsp; String times = "time1, 5:01,3:21,4:05,1:52, time2, 2:11,6:35,2:00,5:00, time3, 12:09,11:35, 9:02";&nbsp; &nbsp; &nbsp; &nbsp; // Set up Objects used to collect&nbsp; &nbsp; &nbsp; &nbsp; String currentKey = "";&nbsp; &nbsp; &nbsp; &nbsp; HashMap<String, List<LocalTime>> timeMap = new HashMap();&nbsp; &nbsp; &nbsp; &nbsp; // Iterate though list&nbsp; &nbsp; &nbsp; &nbsp; String[] lineBreaks = times.split("\n");&nbsp; &nbsp; &nbsp; &nbsp; for(String line : lineBreaks){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String[] csvBreaks = line.split(",");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(String csv : csvBreaks){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //try to parse a time and add it to the key set, add a new key if there is a failure&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeMap.get(currentKey).add(LocalTime.parse(csv.trim(), formatter));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception ex){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentKey = csv;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeMap.put(currentKey, new ArrayList<>());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //Print result:&nbsp; &nbsp; &nbsp; &nbsp; for(Map.Entry<String, List<LocalTime>> entry : timeMap.entrySet()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("times for key: " + entry.getKey());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(LocalTime time : entry.getValue()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("\t" + time);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答