使用OpenCsv读写csv文件

前言:

      openCSV是最简单易懂的CSV解析器之一,它使用标准Reader/Writer类并CSVReader在顶部提供实现。OpenCSV读取CSV的速度比使用Apache Commons CSV读取的速度要快,因为CSVWriter使用该CSVToBean.parse()方法时,将CSV实现为多线程的。

1.引入依赖jar


   com.opencsv
   opencsv
   4.0

2.写csv文件

    private void writerFile() throws Exception {
        String outFileName = "/user/desktop/outFileName.csv";
        Writer writer = Files.newBufferedWriter(Paths.get(outFileName));
        CSVWriter csvWriter = new CSVWriter(writer,
                CSVWriter.DEFAULT_SEPARATOR,
                CSVWriter.NO_QUOTE_CHARACTER,
                CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                CSVWriter.DEFAULT_LINE_END);

        String[] headerRecord = {"id", "name", "phone", "address"};
        csvWriter.writeNext(headerRecord);
        List querys = userMapper.selectAll();
        if (querys != null) {
            for (User suer : querys) {
                csvWriter.writeNext(new String[]{user.getId().toString(),user.getUserName(),user.getPhone(),user.getAddress()});
                System.out.println("count 写入行数:" + count);
                csvWriter.flush();
            }
            csvWriter.close();
        }
    }

3.读csv文件

    private void readCsvFile() throws Exception {
        String fileName = "/user/desktop/readFileName.csv";
        Reader reader = Files.newBufferedReader(Paths.get(fileName));
        CSVReader csvReader = new CSVReader(reader);
        String[] nextRecord;
        while ((nextRecord = csvReader.readNext()) != null) {
            String name = nextRecord[0];
            String age = nextRecord[1];
            String address = nextRecord[2];
            System.out.println("name:" + name + "age:" + age + "address" + address);
        }
    }

使用OpenCsv读写csv文件_第1张图片

你可能感兴趣的:(Java,服务器,java)