我想使用以下代码从csv文件中的数据集中提取数据:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingCSVFiles {
public static void main(String[] args) {
File dataFile = new File("URL\Countries.csv");
try {
@SuppressWarnings("resource")
Scanner input = new Scanner(dataFile);
input.useDelimiter(",|\\s");
String column1 = input.next();
String column2 = input.next();
System.out.printf("%-11s%12s%n", column1, column2);
while (input.hasNext()) {
String Country = input.next();
int Population = input.nextInt();
System.out.printf("%-11s%, 12d%n", Country, Population);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
}不幸的是,我只得到第一行作为输出:
Country Population然后我得到以下错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor (Unknown Source)
at ...下面是csv.file:
Country,Population
Argentina,41343201
Brazil,201103330
Chile,16746491
Columbia,47790000
Paraguay,6375830
Peru,29907003
Venezuela,27223228任何帮助都将不胜感激。
发布于 2018-08-10 23:35:34
将分隔符设置为,或\s,它只匹配一个空格字符。
如果您的文件结尾由两个字符分隔(在Windows系统中是默认的),例如\r\n,它将只使用第一个字符(\r),这意味着下一个标记将是一个空字符串(读入Country),之后的标记将是下一个国家名称,不能读取为整数。
我建议逐行阅读您的输入,然后使用,拆分这些行。
发布于 2018-08-10 23:28:36
使用Apache Commons CSV。如果是出于说教的目的,那么我认为你需要再给next()打个电话
发布于 2018-08-10 23:39:27
这几乎是正确的。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingCSVFiles {
public static void main(String[] args) {
File dataFile = new File("URL\\Countries.csv");
// the resources MUST be closed! Do not suppress these kind of warnings!
try (Scanner input = new Scanner(dataFile)) {
// what you forget is the newline: at the end of the lines, there maybe more than one white space character (on windows,\r\n)
input.useDelimiter(",|\\s+");
String column1 = input.next();
String column2 = input.next();
System.out.printf("columns: %-11s%12s%n", column1, column2);
while (input.hasNextLine()) {
String Country = input.next();
int Population = input.nextInt();
System.out.printf("%-11s%, 12d%n", Country, Population);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}https://stackoverflow.com/questions/51789691
复制相似问题