Java读写csv文件

前言java


对于表格类数据,除了Excel相关的文件格式适合承载外,csv也是很是适合的一种格式。csv是经过逗号等分割符来组织数据的,我的看来,csv具备轻量级、能承载大批量数据、跨平台等特色,对于程序员而言是一种能够不依赖第三方库就能实现读写的文件格式,相关明确的定义能够在百科上找到,CSV百科。PS:程序员导数据若是偷懒的话,csv无疑很是适合。本文以Java语言为例,实现csv格式文件的读写。git

Java读取csv文件内容程序员


使用Java读取csv文件的核心是字符流Reader,经过字符流读取到每一行,每行的内容是逗号分割的字符串,这样经过String的split方法就能获取到每一行中每个单元格的内容。示例以下:github

public static void readCsv(String fileName) {
        try (BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"))) {
            String record;
            while ((record = file.readLine()) != null) {
                System.out.println(record);
                String[] cells = record.split(",");
                for (String cell : cells) {
                    System.out.println(cell);
                }
            }
        } catch (Exception e) {

        }
    }

Java将内容写入到csv文件工具


经过上面读取csv文件的范例,能够反推写入,一样用字符流Writer来写入,每一行的数据经过逗号分割。示例代码以下:excel

public static void writeCSVFile(List<List<String>> dataList, String outPutPath, String filename) {
        File csvFile = new File(outPutPath + File.separator + filename + ".csv");
        try (BufferedWriter csvWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024)) {
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();
            // 写入文件内容
            for (List<String> row : dataList) {
                String line = String.join(",", row);
                csvWriter.write(line);
                csvWriter.newLine();
            }
            csvWriter.flush();
        } catch (Exception e) {

        }
    }

PS:Apache poi 处理excel文件在大批量数据上会有OOM的问题,阿里已经就这个问题封装了本身的工具库,能够在github上搜到,随着数据量上升,用poi技术导出excel文件的效率跟导出csv这样简单的文件格式的效率相比仍是有比较大的差距,之后会补充导出csv和poi导出Excel的Benchmarkcode

相关文章
相关标签/搜索