我在文件中有很多次的列表。我的目标是将所有时间始终放在自己的字符串数组中,称为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
。
答案 0 :(得分:1)
这是一个可以完成您想要的单元测试。我不得不格式化您的输入字符串。您应该能够以最小的更改为您完成这项工作。
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);
}
}
}
}
答案 1 :(得分:1)
这是另一种更简单的方法:
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();
}
}
鉴于问题中显示的输入数据,将产生以下输出:
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]
答案 2 :(得分:1)
由于您确定要精确地使用3个字符串数组,因此下面的代码以“ time”为分隔符来分割初始字符串,并删除了"1, "
,"2, "
,"3, "
首先,修剪并删除,
,最后删除所有空格后,以,
为分隔符将每个项目分割成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个字符串数组:
[5:01, 3:21, 4:05, 1:52]
[2:11, 6:35, 2:00, 5:00]
[12:09, 11:35, 9:02]