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

在Java中,从以逗号和标题分隔的文件读取时间,java,file,Java,File,我有一个文件中有很多次的列表。我的目标是将所有时间放在它们自己的字符串数组中,称为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 我试着将我读到的每一行拆分,然后将其转换为标记,用逗号分隔。但是,目前这似乎不是一个有效的解决方案,因为第一个元素总是以空格开头,最后一个元素没有逗号。我想知道是否有人知道这个问题的解决方法 以下是我

我有一个文件中有很多次的列表。我的目标是将所有时间放在它们自己的字符串数组中,称为
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])
    }
}
}
public void read_文件(){
试一试{
times=新扫描仪(新文件(“times.csv”);
读取_文件();
}
捕获(例外e){
System.out.printf(“找不到文件\n”);
}                
}
公共无效读_文件(){
while(times.hasNextLine()){
i++;
字符串a=times.nextLine();
字符串时间[]=a.split(“,”);
//将只添加前4个元素
if(i<4){
时间列表1.添加(时间[i])
}
}
}

这里的问题是,我不知道如何检查有多少元素我必须继续,因为列表中的次数是不可预测的。唯一保持不变的是,始终会有3个时间列表,分别称为
time1
time2
time3
,下面是一个单元测试,它可以满足您的需求。我必须稍微格式化一下你的输入字符串。你应该能够有这项工作为你与最小的变化

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;

/**
 * @author Dr. Parameter
 */
public class TimeParser {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("k:mm");

    @Test
    public void test(){

        // Test input
        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";

        // Set up Objects used to collect
        String currentKey = "";
        HashMap<String, List<LocalTime>> timeMap = new HashMap();

        // Iterate though list
        String[] lineBreaks = times.split("\n");
        for(String line : lineBreaks){
            String[] csvBreaks = line.split(",");
            for(String csv : csvBreaks){

                //try to parse a time and add it to the key set, add a new key if there is a failure
                try {
                    timeMap.get(currentKey).add(LocalTime.parse(csv.trim(), formatter));
                } catch (Exception ex){
                    currentKey = csv;
                    timeMap.put(currentKey, new ArrayList<>());
                }
            }
        }

        //Print result:
        for(Map.Entry<String, List<LocalTime>> entry : timeMap.entrySet()){
            System.out.println("times for key: " + entry.getKey());
            for(LocalTime time : entry.getValue()){
                System.out.println("\t" + time);
            }
        }
    }
}
import org.junit.Test;
导入java.time.LocalDate;
导入java.time.LocalTime;
导入java.time.format.DateTimeFormatter;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
/**
*@author博士参数
*/
公共类时间分析器{
私有最终DateTimeFormatter formatter=模式的DateTimeFormatter.of(“k:mm”);
@试验
公开无效测试(){
//测试输入
字符串时间=“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”;
//设置用于收集的对象
字符串currentKey=“”;
HashMap timeMap=新HashMap();
//遍历列表
String[]lineBreaks=times.split(“\n”);
用于(字符串行:换行符){
字符串[]csvBreaks=line.split(“,”);
用于(字符串csv:csvBreaks){
//尝试解析时间并将其添加到密钥集,如果出现故障,请添加新密钥
试一试{
获取(currentKey).add(LocalTime.parse(csv.trim(),格式化程序));
}捕获(例外情况除外){
currentKey=csv;
put(currentKey,newarraylist());
}
}
}
//打印结果:
对于(Map.Entry:timeMap.entrySet()){
System.out.println(“键的时间:+entry.getKey());
for(LocalTime:entry.getValue()){
System.out.println(“\t”+时间);
}
}
}
}

这里有一个单元测试,它可以满足您的需要。我必须稍微格式化一下你的输入字符串。你应该能够有这项工作为你与最小的变化

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;

/**
 * @author Dr. Parameter
 */
public class TimeParser {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("k:mm");

    @Test
    public void test(){

        // Test input
        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";

        // Set up Objects used to collect
        String currentKey = "";
        HashMap<String, List<LocalTime>> timeMap = new HashMap();

        // Iterate though list
        String[] lineBreaks = times.split("\n");
        for(String line : lineBreaks){
            String[] csvBreaks = line.split(",");
            for(String csv : csvBreaks){

                //try to parse a time and add it to the key set, add a new key if there is a failure
                try {
                    timeMap.get(currentKey).add(LocalTime.parse(csv.trim(), formatter));
                } catch (Exception ex){
                    currentKey = csv;
                    timeMap.put(currentKey, new ArrayList<>());
                }
            }
        }

        //Print result:
        for(Map.Entry<String, List<LocalTime>> entry : timeMap.entrySet()){
            System.out.println("times for key: " + entry.getKey());
            for(LocalTime time : entry.getValue()){
                System.out.println("\t" + time);
            }
        }
    }
}
import org.junit.Test;
导入java.time.LocalDate;
导入java.time.LocalTime;
导入java.time.format.DateTimeFormatter;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
/**
*@author博士参数
*/
公共类时间分析器{
私有最终DateTimeFormatter formatter=模式的DateTimeFormatter.of(“k:mm”);
@试验
公开无效测试(){
//测试输入
字符串时间=“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”;
//设置用于收集的对象
字符串currentKey=“”;
HashMap timeMap=新HashMap();
//遍历列表
String[]lineBreaks=times.split(“\n”);
用于(字符串行:换行符){
字符串[]csvBreaks=line.split(“,”);
用于(字符串csv:csvBreaks){
//尝试解析时间并将其添加到密钥集,如果出现故障,请添加新密钥
试一试{
获取(currentKey).add(LocalTime.parse(csv.trim(),格式化程序));
}捕获(例外情况除外){
currentKey=csv;
put(currentKey,newarraylist());
}
}
}
//打印结果:
对于(Map.Entry:timeMap.entrySet()){
System.out.println(“键的时间:+entry.getKey());
for(LocalTime:entry.getValue()){
System.out.println(“\t”+时间);
}
}
}
}

下面是另一个更简单的方法:

public class ReadTimes {
    private Map<String, List<String>> timeLists = new HashMap();
    public void read_file() {
        try {
            Scanner times = new Scanner(new File("times.csv"));
            read_file(times);
        } catch (Exception e) {
            System.out.printf("Could not find file\n");
        }
    }
    public void read_file(Scanner times) {
        String label=null;
        while (times.hasNextLine()) {
            String time[] = times.nextLine().trim().split("[, ]+");
            for (String timeString : time) {
                if (timeString.startsWith("time")) {
                    label = timeString;
                    timeLists.put(label, new ArrayList());
                } else if (label != null) {
                    timeLists.get(label).add(timeString);
                }
            }
        }
        // dump the map of arraylists for demonstration purposes...
        for (Entry<String,List<String>> timeEntry : timeLists.entrySet()) {
            System.out.println(timeEntry);
        }
    }

    public static void main(String[] args) {
        ReadTimes rt = new ReadTimes();
        rt.read_file();
    }
}

下面是另一个更简单的方法:

public class ReadTimes {
    private Map<String, List<String>> timeLists = new HashMap();
    public void read_file() {
        try {
            Scanner times = new Scanner(new File("times.csv"));
            read_file(times);
        } catch (Exception e) {
            System.out.printf("Could not find file\n");
        }
    }
    public void read_file(Scanner times) {
        String label=null;
        while (times.hasNextLine()) {
            String time[] = times.nextLine().trim().split("[, ]+");
            for (String timeString : time) {
                if (timeString.startsWith("time")) {
                    label = timeString;
                    timeLists.put(label, new ArrayList());
                } else if (label != null) {
                    timeLists.get(label).add(timeString);
                }
            }
        }
        // dump the map of arraylists for demonstration purposes...
        for (Entry<String,List<String>> timeEntry : timeLists.entrySet()) {
            System.out.println(timeEntry);
        }
    }

    public static void main(String[] args) {
        ReadTimes rt = new ReadTimes();
        rt.read_file();
    }
}

由于您确定只需要3个字符串数组,下面的代码以“time”作为分界符拆分初始字符串,删除开头的
“1”、“
“2”、“
”3、
,最后在删除所有空格后以
拆分每个项目,
作为一个delimeter生成3个字符串数组

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

    String[] splitted = times.split("time");

    // exclude 0th item which is ""
    for (int i = 1; i < splitted.length; i++) {
        splitted[i] = splitted[i].trim();

        int index = splitted[i].indexOf(" ");

        if (splitted[i].endsWith(","))
            splitted[i] = splitted[i].substring(index + 1, splitted[i].length() - 1);
        else
            splitted[i] = splitted[i].substring(index + 1);

        splitted[i] = splitted[i].replaceAll(" ", "");
    }

    try {  // just in case
        String time1[] = splitted[1].split(",");
        System.out.println(Arrays.toString(time1));
        String time2[] = splitted[2].split(",");
        System.out.println(Arrays.toString(time2));
        String time3[] = splitted[3].split(",");
        System.out.println(Arrays.toString(time3));
    } catch (Exception e) {
        e.printStackTrace();
    }

由于您确定只需要3个字符串数组,下面的代码以“time”作为分界符拆分初始字符串,删除开头的
“1”、“
“2”、“
”3、
,最后在删除所有空格后以
拆分每个项目,
作为一个delimeter生成3个字符串数组

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

    String[] splitted = times.split("time");

    // exclude 0th item which is ""
    for (int i = 1; i < splitted.length; i++) {
        splitted[i] = splitted[i].trim();

        int index = splitted[i].indexOf(" ");

        if (splitted[i].endsWith(","))
            splitted[i] = splitted[i].substring(index + 1, splitted[i].length() - 1);
        else
            splitted[i] = splitted[i].substring(index + 1);

        splitted[i] = splitted[i].replaceAll(" ", "");
    }

    try {  // just in case
        String time1[] = splitted[1].split(",");
        System.out.println(Arrays.toString(time1));
        String time2[] = splitted[2].split(",");
        System.out.println(Arrays.toString(time2));
        String time3[] = splitted[3].split(",");
        System.out.println(Arrays.toString(time3));
    } catch (Exception e) {
        e.printStackTrace();
    }

那么,你为什么不先通过使用找到每个“时间列表”的开始位置来拆分你的行以提取time1、time2、time3?这个文件是你收到的csv还是你制作的csv?您确定没有逗号或引号吗?您可能想看看如何使用csv解析器,比如:那么,为什么不首先通过使用查找eac的位置来拆分行以提取time1、time2、time3