首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用Java读取CSV文件(SE8)

用Java读取CSV文件(SE8)
EN

Stack Overflow用户
提问于 2018-08-10 23:25:00
回答 4查看 261关注 0票数 0

我想使用以下代码从csv文件中的数据集中提取数据:

代码语言:javascript
运行
复制
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);
}
}
}

不幸的是,我只得到第一行作为输出:

代码语言:javascript
运行
复制
Country           Population

然后我得到以下错误:

代码语言:javascript
运行
复制
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor (Unknown Source)
    at ...

下面是csv.file:

代码语言:javascript
运行
复制
Country,Population
Argentina,41343201
Brazil,201103330
Chile,16746491
Columbia,47790000
Paraguay,6375830
Peru,29907003
Venezuela,27223228

任何帮助都将不胜感激。

EN

回答 4

Stack Overflow用户

发布于 2018-08-10 23:35:34

将分隔符设置为,\s,它只匹配一个空格字符。

如果您的文件结尾由两个字符分隔(在Windows系统中是默认的),例如\r\n,它将只使用第一个字符(\r),这意味着下一个标记将是一个空字符串(读入Country),之后的标记将是下一个国家名称,不能读取为整数。

我建议逐行阅读您的输入,然后使用,拆分这些行。

票数 1
EN

Stack Overflow用户

发布于 2018-08-10 23:28:36

使用Apache Commons CSV。如果是出于说教的目的,那么我认为你需要再给next()打个电话

票数 0
EN

Stack Overflow用户

发布于 2018-08-10 23:39:27

这几乎是正确的。

代码语言:javascript
运行
复制
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();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51789691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档