使用Java(SE8)读取CSV文件

时间:2018-08-10 15:25:00

标签: java csv

我想使用以下代码从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

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:1)

您将分隔符设置为\s\r\n,它们仅与一个空格字符匹配。

如果文件结尾以两个字符分隔(在Windows系统中为默认字符),例如\r,它将仅使用第一个字符(Country),这意味着下一个令牌将是一个空字符串(读入,),此后的令牌将是下一个国家/地区名称,不能将其读取为整数。

建议您逐行阅读输入内容,然后使用{{1}}拆分这些行。

答案 1 :(得分:0)

使用Apache Commons CSV。如果是出于教学目的,那么我认为您需要再次致电next()

答案 2 :(得分:0)

那几乎是正确的。

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();
        }
    }
}

答案 3 :(得分:0)

您可以使用opencsv lib http://opencsv.sourceforge.net/,只需创建

之类的DTO。
 public class CountryAndPopulationDTO implements Serializable{

 private String country ;
 private String population;

 // getter & setter 
 }

// in your main

FileReader filereader = new FileReader(dataFile);
CSVReader reader = new CSVReader(filereader, ',');
Map<String, String> columnMapping = new HashMap<String, String>();

columnMapping.put("country", "country");
columnMapping.put("population", "population");

HeaderColumnNameTranslateMappingStrategy<CountryAndPopulationDTO> strategy = new HeaderColumnNameTranslateMappingStrategy<CountryAndPopulationDTO>();
strategy.setType(CountryAndPopulationDTO.class);
strategy.setColumnMapping(columnMapping);
List<CountryAndPopulationDTO> countryAndPopulationDTOList= new ArrayList<CountryAndPopulationDTO>();
try {
CsvToBean<CountryAndPopulationDTO> csv = new CsvToBean<CountryAndPopulationDTO>() {
    protected Object convertValue(String value, PropertyDescriptor prop) throws InstantiationException, IllegalAccessException {
        if (StringUtils.isEmpty(value)) {
            value = null;
        }
        return super.convertValue(value, prop);
    }
};
log.info(" -----------------  MAPPING CSV FILE  ----------------------------");
countryAndPopulationDTOList = csv.parse(strategy, reader); 

}catch (Exception e) {
 throw new Exception("Mapping problem --> ", e.getCause());
}

//现在countryAndPopulationDTOList拥有您的所有数据:)