Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to read and write csv files in Java

Shulou Source: shulou.com Published: 2022-06-02 11:08:13 10月03日 Update

How to read and write csv files in Java? in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.

Java reads the contents of csv file

The core of using Java to read csv files is the character stream Reader, which reads each line through the character stream, and the content of each line is a comma-separated string, so that the contents of each cell in each line can be obtained through the split method of String. Examples are as follows:

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 writes the content to the csv file

With the above example of reading a csv file, you can reverse the write, also using the character stream Writer, with each line of data separated by a comma. The sample code is as follows:

Public static void writeCSVFile (List 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 (); / / write file content for (List row: dataList) {String line = String.join (",", row); csvWriter.write (line); csvWriter.newLine ();} csvWriter.flush () } catch (Exception e) {}}

PS:Apache poi will have the problem of OOM in dealing with excel files in large quantities of data. Ali has encapsulated his own tool library for this problem, which can be found on github. With the increase in the amount of data, there is still a big gap between the efficiency of exporting excel files with poi technology and the efficiency of exporting simple file formats such as csv. In the future, we will supplement the Benchmark of exporting csv and poi exporting Excel.

This is the answer to the question about how to read and write csv documents in Java. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Tags: File content question line character data efficiency method more example comma UTF-8 help solution easy easy code unit mass string Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Apple MySQL Xiaomi Linux