Save file csv java

How to read and write CSV files using core Java

In earlier articles, I explained how to read and writing CSV files using OpenCSV as well as Apache Commons CSV library.

This article is the last one in our short series to learn about 3rd-party libraries and core Java APIs for efficiently reading and writing CSV files.

A CSV file is a plain-text file that stores data in a tabular format, where columns are separated by a delimiter (usually a comma , or a tab). These files are a common choice for importing and exporting data between servers and applications.

In this article, you’ll learn how to read and write CSV files using core Java without using any 3rd-party library.

Two important problems that we may face while reading and parsing CSV files:

  1. The field value contains the delimiter. For example, a comma is used as a separator, and the field value containing commas: 1, «Greta, Jones», UK
  2. The field value contains double-quotes, and the double-quotes are used to wrap field values. In such a case, according to RFC 4180, a double-quote that appears inside the field value must be properly-escaped by preceding it with another double-quote: «1», «Greta»»Jones», «UK»

If your CSV file contains any of the above things, you should use a 3rd-party library like OpenCSV for reading the CSV file.

Читайте также:  Description watching server java lang error watchdog

Third-party libraries are definitely a better choice for handling different CSV formats, delimiters, and special characters.

However, not all CSV files have such problems. For simple CSV files (without double-quotes and delimiters in field values), core Java is sufficient.

Here is how our sample CSV file looks:

1,John Deo,john@example.com,US 2,Alex Jones,alex@example.com,DE 3,Jovan Lee,jovan@example.com,FR 4,Greg Hover,greg@example.com,US 4,Emma Watson,emma@example.com,CA 

The Scanner class in Java breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

try  // create scanner instance Scanner scanner = new Scanner(Paths.get("users.csv").toFile()); // set comma as delimiter scanner.useDelimiter(","); // read all fields while (scanner.hasNext())  System.out.print(scanner.next() + " "); > //close the scanner scanner.close(); > catch (FileNotFoundException ex)  ex.printStackTrace(); > 
1 John Deo john@example.com US 2 Alex Jones alex@example.com DE 3 Jovan Lee jovan@example.com FR 4 Greg Hover greg@example.com US 4 Emma Watson emma@example.com CA 

Another way of reading and parsing a CSV file is by using a combination of the BufferedReader class and the String.split() method:

try  // CSV file delimiter String DELIMITER = ","; // create a reader BufferedReader br = Files.newBufferedReader(Paths.get("users.csv")); // read the file line by line String line; while ((line = br.readLine()) != null)  // convert line into tokens String[] tokens = line.split(DELIMITER); // TODO: do something here with the data // print all tokens for (String token : tokens)  System.out.println(token); > > // close the reader br.close(); > catch (IOException ex)  ex.printStackTrace(); > 
  • Open the CSV file for reading by using the Files.newBufferedReader() method.
  • Create an instance of BufferedReader to read the file line by line until the end of file (EOF) is reached.
  • Use the String.split() method to convert each line into multiple tokens by using the comma ( , ) as a delimiter.
  • The tokens array should contain a list of fields found in each the CSV file row. You should use this array to process the CSV record; like saving it to a database or storing in a Java collection for later use.

Writing data to a CSV file is like writing to any other text file in Java. The simplest way is to use the FileWriter class. This is a convenience class for writing streams of characters. The following example demonstrates how to write a List of objects to a CSV file using the FileWriter in Java:

try  // create a list of objects ListListString>> records = Arrays.asList( Arrays.asList("1", "John Lee", "US"), Arrays.asList("2", "Jovan Roover", "DE"), Arrays.asList("3", "Emma Watson", "UK") ); // create a writer BufferedWriter writer = Files.newBufferedWriter(Paths.get("users-with-header.csv")); // write header record writer.write("ID,Name,Country"); writer.newLine(); // write all records for (ListString> record : records)  writer.write(String.join(",", record)); writer.newLine(); > //close the writer writer.close(); > catch (IOException ex)  ex.printStackTrace(); > 
ID,Name,Country 1,John Lee,US 2,Jovan Roover,DE 3,Emma Watson,UK 

In this tutorial, we learned how to read and write CSV files using core Java without any 3rd-party library. You can use either the Scanner class or BufferedReader to read and parse a CSV file line by line. For writing to CSV files, you should use the FileWriter class. This solution is intended for reading and writing simple CSV files. For complex CSV files with multiple delimiters, double-quotes, and special characters, you should use 3rd-party libraries.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Как экспортировать данные в файл CSV — Java

csv-writing

ФайлComma-Separated Values (CSV) — это просто обычный текстовый файл, в котором данные хранятся по столбцу за столбцом и разделены разделителями (запятыми).

Note
Запись файла CSV аналогична написанию обычного текстового файла, только остерегайтесь проблемы «двойных кавычек», о которой я упоминал в моих предыдущихCSV parsing example.

В этом руководстве мы покажем вам простой класс CVSUtils для простой записи данных или объектов в файл CVS.

1. Пример написания CSV

1.1 Review the following CVSUtils class, it supports custom separator, custom enclose quote (default is empty), escaped the double-quotes with another double quote (RFC4180)

package com.example.utils; import java.io.IOException; import java.io.Writer; import java.util.List; public class CSVUtils < private static final char DEFAULT_SEPARATOR = ','; public static void writeLine(Writer w, Listvalues) throws IOException < writeLine(w, values, DEFAULT_SEPARATOR, ' '); >public static void writeLine(Writer w, List values, char separators) throws IOException < writeLine(w, values, separators, ' '); >//https://tools.ietf.org/html/rfc4180 private static String followCVSformat(String value) < String result = value; if (result.contains("\"")) < result = result.replace("\"", "\"\""); >return result; > public static void writeLine(Writer w, List values, char separators, char customQuote) throws IOException < boolean first = true; //default customQuote is empty if (separators == ' ') < separators = DEFAULT_SEPARATOR; >StringBuilder sb = new StringBuilder(); for (String value : values) < if (!first) < sb.append(separators); >if (customQuote == ' ') < sb.append(followCVSformat(value)); >else < sb.append(customQuote).append(followCVSformat(value)).append(customQuote); >first = false; > sb.append("\n"); w.append(sb.toString()); > >

1.2 Example to show the CSVUtils usage.

package com.example.utils; import java.io.FileWriter; import java.util.Arrays; public class CVSUtilExample < public static void main(String[] args) throws Exception < String csvFile = "/Users/example/csv/abc.csv"; FileWriter writer = new FileWriter(csvFile); CSVUtils.writeLine(writer, Arrays.asList("a", "b", "c", "d")); //custom separator + quote CSVUtils.writeLine(writer, Arrays.asList("aaa", "bb,b", "cc,c"), ',', '"'); //custom separator + quote CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc,c"), '|', '\''); //double-quotes CSVUtils.writeLine(writer, Arrays.asList("aaa", "bbb", "cc\"c")); writer.flush(); writer.close(); >>
a,b,c,d "aaa","bb,b","cc,c" 'aaa'|'bbb'|'cc,c' aaa,bbb,cc""c

2. Больше примеров

Давайте рассмотрим другой пример, он создает список объектов и записывает его в файл CSV.

package com.example.csv; import java.math.BigDecimal; public class Developer < private String name; private BigDecimal salary; private int age; public Developer(String name, BigDecimal salary, int age) < this.name = name; this.salary = salary; this.age = age; >//. >
package com.example.utils; import com.example.java8.Developer; import java.io.FileWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CVSUtilExample < public static void main(String[] args) throws Exception < String csvFile = "/Users/example/csv/developer.csv"; FileWriter writer = new FileWriter(csvFile); Listdevelopers = Arrays.asList( new Developer("example", new BigDecimal(120500), 32), new Developer("zilap", new BigDecimal(150099), 5), new Developer("ultraman", new BigDecimal(99999), 99) ); //for header CSVUtils.writeLine(writer, Arrays.asList("Name", "Salary", "Age")); for (Developer d : developers) < Listlist = new ArrayList<>(); list.add(d.getName()); list.add(d.getSalary().toString()); list.add(String.valueOf(d.getAge())); CSVUtils.writeLine(writer, list); //try custom separator and quote. //CSVUtils.writeLine(writer, list, '|', '\"'); > writer.flush(); writer.close(); > >
Name,Salary,Age example,120500,32 zilap,150099,5 ultraman,99999,99

Note
Если вам все еще неудобно реализовать себя, попробуйте эту стороннюю библиотеку CSV -OpenCSV.

Источник

Write Strings to CSV File in Java

Write Strings to CSV File in Java

  1. Using PrintWriter to Read and Write Into a CSV File in Java
  2. Using OpenCSV Library to Read and Write Into a CSV File in Java

CSV stands for Comma Separated Values ; it’s a commonly used format for bulky data transfers between systems. There are also many parser libraries to be used along with Java to be able to work with this format.

Using PrintWriter to Read and Write Into a CSV File in Java

The PrinterWriter function in Java is a writer class used to print formatted representation of objects to a text-output stream. We create a writer object passing a new file named test.csv as the destination for the writer. Here, the sb object appends a specified string to the character sequence.

The write() method on the writer instance writes the textual content into the stream. The flush() method flushes the contents into the file, and the close() method permanently closes the stream. We can also read the contents of the test.csv file.

The readCSVFile() method is called on the TestCSV class instance. Here, we created an instance of the Scanner class with values from the specified file. It breaks data into tokens using a delimiter pattern. The hasNextLine() returns true if the scanner has another line of input. Thus, we read each line of token data using the next() method and store it in an array, finally printing the output.

import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner;  public class TestCSV   public static void main(String args[])  try (PrintWriter writer = new PrintWriter(new File("test.csv")))    StringBuilder sb = new StringBuilder();  sb.append("id");  sb.append(',');  sb.append("Name");  sb.append(',');  sb.append("Address");  sb.append('\n');   sb.append("101");  sb.append(',');  sb.append("John Doe");  sb.append(',');  sb.append("Las Vegas");  sb.append('\n');   writer.write(sb.toString());  writer.close();  System.out.println("done!");   > catch (FileNotFoundException e)   System.out.println(e.getMessage());  >  TestCSV testCSV = new TestCSV();  testCSV.readCSVFile();  >   public void readCSVFile()  List> records = new ArrayList<>();  try (Scanner scanner = new Scanner(new File("test.csv"));)   while (scanner.hasNextLine())   records.add(getRecordFromLine(scanner.nextLine()));  >  > catch (FileNotFoundException e)   e.printStackTrace();  >  System.out.println(records.toString());  >  private List getRecordFromLine(String line)   List values = new ArrayList();  try (Scanner rowScanner = new Scanner(line))   rowScanner.useDelimiter(",");  while (rowScanner.hasNext())   values.add(rowScanner.next());  >  >  return values;  >  > 
done! [[id, Name, Address], [101, John Doe, Las Vegas]] 

Using OpenCSV Library to Read and Write Into a CSV File in Java

The maven dependency for this library is given below:

   com.opencsv   opencsv   5.4  

The OpenCsv is a simple parser library for java; it has a set of OpenCsv classes which we use to read and write to a CSV file. In the main() method, we first call the method to write to a CSV file using the CSVWriter class. This class is used to write CSV data to writer implementation.

We create a writer instance of CSVWriter and call the writeNext() function on this object to generate a CSV file with data from an array of strings separated using a delimiter. The close() method closes the writer stream.

To read the data from the file we created in the CSV format, we call the readCSVFile method on the main class object, where we parse the CSV file. To read all the records into a list at once, we use the readAll() method. We loop over each record and print it out.

import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import com.opencsv.exceptions.CsvException; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.List;  public class CSVLibrary   public static void main (String args[])   CSVLibrary csvLibrary = new CSVLibrary();  csvLibrary.writeToCsv();  csvLibrary.readCSVFile();  >  public void writeToCsv()  String csv = "data.csv";  try  CSVWriter writer = new CSVWriter(new FileWriter(csv));  String [] record = "2,Virat,Kohli,India,30".split(",");  writer.writeNext(record);   writer.close();  >catch (IOException e)   e.printStackTrace();  >   >  public void readCSVFile()  CSVReader reader = null;  try   reader = new CSVReader(new FileReader("data.csv"));  > catch (FileNotFoundException e)   e.printStackTrace();  >   ListString[]> allRows = null;  try   allRows = reader.readAll();  > catch (IOException e)   e.printStackTrace();  > catch (CsvException e)   e.printStackTrace();  >   for(String[] row : allRows)  System.out.println(Arrays.toString(row));  >  > > 

Источник

Оцените статью