gpt4 book ai didi

java - 使用 Java 解析 Csv 文件时出错

转载 作者:行者123 更新时间:2023-12-01 18:43:23 25 4
gpt4 key购买 nike

我有一个 csv 文件,其值如下:

1/1/1983;1,7;-3;8;-0,7;84;4;2;11;0;1030;0;0
2/1/1983;2,7;-2;8,4;1,9;94;2;2;15;0;1027;0;0
3/1/1983;4,1;-0,4;11,3;3,1;93;3;3;13;0;1030;0;0
4/1/1983;7,6;1,3;15;5,1;84;9;8;28;0;1027;0;0
5/1/1983;5,6;1,4;10;5,1;97;2;2;11;0;1023;0;0
6/1/1983;7;5,5;7,5;7;100;1;3;9;0;1028;0;0
7/1/1983;7,7;5;13,4;7,1;96;1;4;20;0;1029;0;0
8/1/1983;7,9;7;15,5;7,4;97;2;7;24;0;1029;0;1
9/1/1983;6,7;1;10,3;4,1;83;8;15;44;0;1033;0;0,3
10/1/1983;2,2;-1,9;8;0,4;88;8;4;13;0;1036;0;0
11/1/1983;0,7;-3,4;6,4;-1,2;87;3;1;13;0;1038;0;0
12/1/1983;0,2;-4,7;8;-1,7;87;6;4;9;0;1037;0;0
13/1/1983;1,7;-5,2;11,1;-0,1;88;4;3;15;0;1032;0;

所以我在网站上找到了一个 Csv Parser 实现:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class ScannerExample
{
public static void main(String[] args) throws FileNotFoundException
{
//Array
ArrayList<String> weather = new ArrayList<String>();
//Get scanner instance
Scanner scanner = new Scanner(new File("C:/csv/meteo2.csv"));

//Set the delimiter used in file
scanner.useDelimiter(";");

//Get all tokens and store them in some data structure
//I am just printing them
while (scanner.hasNext())
{
weather.add(scanner.next());
}
System.out.println(weather.get(12));
//Do not forget to close the scanner
scanner.close();
}
}

但是我对一行最后一个元素连续行第一个元素有问题>:事实上,在代码中我尝试打印第十二个元素(必须是 0)。它打印

0
2/1/1983

但它仅被视为一个元素。有解决办法吗?

最佳答案

如果您想要分号和换行符作为分隔符,则应该使用

scanner.useDelimiter("[;\n]");

Scanner#useDelimiter(String pattern)需要正则表达式作为参数。

关于java - 使用 Java 解析 Csv 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18979123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com