Java csv file to string

Read / Write CSV file in Java

If you want to work with Comma-separated Files (CSV) in Java, here’s a quick API for you. As Java doesn’t support parsing of CSV files natively, we have to rely on third party library. Opencsv is one of the best library available for this purpose. It’s open source and is shipped with Apache 2.0 licence which makes it possible for commercial use. Let’s us see different APIs to parse CSV file. Before that we will need certain tools for this example:

Tools & Technologies

  1. Java JDK 1.5 or above
  2. OpenCSV library v1.8 or above (download)
  3. Eclipse 3.2 above (optional)

1. Reading CSV file in Java

We will use following CSV sample file for this example: File: sample.csv

COUNTRY,CAPITAL,POPULATION India,New Delhi, 1.21B People's republic of China,Beijing, 1.34B United States,Washington D.C., 0.31B
Code language: PHP (php)

Read CSV file line by line:

String csvFilename = "C:\\sample.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); String[] row = null; while((row = csvReader.readNext()) != null) < System.out.println(row[0] + " # " + row[1] + " # " + row[2]); > //. csvReader.close();
Code language: Java (java)

In above code snippet, we use readNext() method of CSVReader class to read CSV file line by line. It returns a String array for each value in row. It is also possible to read full CSV file once. The readAll() method of CSVReader class comes handy for this.

String[] row = null; String csvFilename = "C:\\work\\sample.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); List content = csvReader.readAll(); for (Object object : content) < row = (String[]) object; System.out.println(row[0] + " # " + row[1] + " # " + row[2]); > //. csvReader.close();
Code language: Java (java)

The readAll() method returns a List of String[] for given CSV file. Both of the above code snippet prints output: Output

COUNTRY # CAPITAL # POPULATION India # New Delhi # 1.21B People's republic of China # Beijing # 1.34B United States # Washington D.C. # 0.31B
Code language: PHP (php)

Use different separator and quote characters If you want to parse a file with other delimiter like semicolon (;) or hash (#), you can do so by calling a different constructor of CSVReader class:

CSVReader reader = new CSVReader(new FileReader(file), ';') //or CSVReader reader = new CSVReader(new FileReader(file), '#')
Code language: Java (java)

Also if your CSV file’s value is quoted with single quote (‘) instead of default double quote (“), then you can specify it in constructor:

CSVReader reader = new CSVReader(new FileReader(file), ',', '\'')
Code language: Java (java)

Also it is possible to skip certain lines from the top of CSV while parsing. You can provide how many lines to skip in CSVReader’s constructor. For example the below reader will skip 5 lines from top of CSV and starts processing at line 6.

CSVReader reader = new CSVReader(new FileReader(file), ',', '\'', 5);
Code language: Java (java)

2. Writing CSV file in Java

Creating a CSV file is as simple as reading one. All you have to do is it create the data list and write using CSVWriter class. Below is the code snippet where we write one line in CSV file.

String csv = "C:\\output.csv"; CSVWriter writer = new CSVWriter(new FileWriter(csv)); String [] country = "India#China#United States".split("#"); writer.writeNext(country); writer.close();
Code language: Java (java)

We created object of class CSVWriter and called its writeNext() method. The writeNext() methods takes String [] as argument. You can also write a List of String[] to CSV directly. Following is code snippet for that.

String csv = "C:\\output2.csv"; CSVWriter writer = new CSVWriter(new FileWriter(csv)); List data = new ArrayList(); data.add(new String[] "India", "New Delhi">); data.add(new String[] "United States", "Washington D.C">); data.add(new String[] "Germany", "Berlin">); writer.writeAll(data); writer.close();
Code language: Java (java)

We used writeAll() method of class CSVWriter to write a List of String[] as CSV file.

3. Mapping CSV with Java beans

In above examples we saw how to parse CSV file and read the data in it. We retrieved the data as String array. Each record got mapped to String. It is possible to map the result to a Java bean object. For example we created a Java bean to store Country information. Country.java – The bean object to store Countries information.

package net.viralpatel.java; public class Country < private String countryName; private String capital; public String getCountryName() < return countryName; > public void setCountryName(String countryName) < this.countryName = countryName; > public String getCapital() < return capital; > public void setCapital(String capital) < this.capital = capital; > >
Code language: Java (java)

Now we can map this bean with Opencsv and read the CSV file. Check out below example:

ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy(); strat.setType(Country.class); String[] columns = new String[] "countryName", "capital">; // the fields to bind do in your JavaBean strat.setColumnMapping(columns); CsvToBean csv = new CsvToBean(); String csvFilename = "C:\\sample.csv"; CSVReader csvReader = new CSVReader(new FileReader(csvFilename)); List list = csv.parse(strat, csvReader); for (Object object : list)
Code language: Java (java)

Check how we mapped Country class using ColumnPositionMappingStrategy . Also the method setColumnMapping is used to map individual property of Java bean to the CSV position. In this example we map first CSV value to countryName attribute and next to capital .

4. Dumping SQL Table as CSV

OpenCSV also provides support to dump data from SQL table directly to CSV. For this we need ResultSet object. Following API can be used to write data to CSV from ResultSet.

java.sql.ResultSet myResultSet = getResultSetFromSomewhere(); writer.writeAll(myResultSet, includeHeaders);
Code language: Java (java)

The writeAll(ResultSet, boolean) method is utilized for this. The first argument is the ResultSet which you want to write to CSV file. And the second argument is boolean which represents whether you want to write header columns (table column names) to file or not.

Источник

Parse and Read a CSV File in Java

A CSV file is used to store tabular data in plain-text form. A comma delimiter is used to identify and separate different data tokens in the CSV file.

  • CSV (Comma Separated Values) files are used by consumers, businesses, and scientific applications. Among its most common uses is moving tabular data between programs in runtime that natively operate on incompatible formats.
  • CSV data is popular because so many programs and languages support some variation of CSV at least as an alternative import/export format.

In Java, there are different ways of reading and parsing CSV files. Let us discuss some of the best approaches:

OpenCSV is a brilliant library for operating on CSV files. It has the following features:

  • Reading arbitrary numbers of values per line
  • Ignoring commas in quoted elements
  • Handling entries that span multiple lines
  • Configurable separator and quote characters
  • Read all the entries at once, or use an Iterator-style model

Import the latest version of OpenCSV into project dependencies.

Example 1: Reading the CSV File line by line into String[]

In the given example, we are using CSVReader class from OpenCSV library which wraps a FileReader for reading the actual CSV file. The file uses the delimiter comma.

  • Using the reader.readNext() , we read the CSV file line by line.
  • It throws IOException if an error occurs in reading the file.
  • It throws CsvValidationException if the read line is not a valid CSV string.
  • When all the lines are read, readNext() method returns null and the program terminates.
try(CSVReader reader = new CSVReader(new FileReader("SampleCSVFile.csv"))) < String [] nextLine; //Read one line at a time while ((nextLine = reader.readNext()) != null) < //Use the tokens as required System.out.println(Arrays.toString(nextLine)); >> catch (IOException | CsvValidationException e)

2. Using Super CSV Library

Super CSV is to be the foremost, fastest, and most programmer-friendly, free CSV package for Java. It supports a very long list of useful features out of the box, such as:

  • Ability to read and write data as POJO classes
  • Automatic encoding and decoding of special characters
  • Custom delimiter, quote character and line separator
  • Support for cell processors to process each token in a specific manner
  • Ability to apply one or more constraints, such as number ranges, string lengths or uniqueness
  • Ability to process CSV data from files, strings, streams and even zip files

Add the latest version of the latest version of Super CSV in the project.

 net.sf.supercsv super-csv 2.4.0 

Example 2: Reading the CSV File into POJO

We will read the following CSV file.

CustomerId,CustomerName,Country,PinCode,Email 10001,Lokesh,India,110001,abc@gmail.com 10002,John,USA,220002,def@gmail.com 10003,Blue,France,330003,ghi@gmail.com

The corresponding POJO class is:

Remember that the column names should match up exactly with the bean’s field names, and the bean has the appropriate setters defined for each field.

import java.io.FileReader; import java.io.IOException; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ParseInt; import org.supercsv.cellprocessor.ParseLong; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.constraint.StrRegEx; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.io.CsvBeanReader; import org.supercsv.io.ICsvBeanReader; import org.supercsv.prefs.CsvPreference; public class ReadCSVFileExample < static final String CSV_FILENAME = "data.csv"; public static void main(String[] args) throws IOException < try(ICsvBeanReader beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE)) < // the header elements are used to map the values to the bean final String[] headers = beanReader.getHeader(true); //final String[] headers = new String[]; final CellProcessor[] processors = getProcessors(); Customer customer; while ((customer = beanReader.read(Customer.class, headers, processors)) != null) < System.out.println(customer); >> > /** * Sets up the processors used for the examples. */ private static CellProcessor[] getProcessors() < final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; StrRegEx.registerMessage(emailRegex, "must be a valid email address"); final CellProcessor[] processors = new CellProcessor[] < new NotNull(new ParseInt()), // CustomerId new NotNull(), // CustomerName new NotNull(), // Country new Optional(new ParseLong()), // PinCode new StrRegEx(emailRegex) // Email >; return processors; > >

The Scanner class breaks its input into tokens using a specified delimiter pattern. The default delimiter is whitespace.

  • We can use a separate Scanner to read lines, and another scanner to parse each line into tokens. This approach may not be useful for large files because it is creating one scanner instance per line.
  • We can use the delimiter comma to parse the CSV file.
  • The CSV tokens may then be converted into values of different datatypes using the various next() methods.

Example 3: Parsing a CSV file using Scanner

try(Scanner scanner = new Scanner(new File("SampleCSVFile.csv"))) < //Read line while (scanner.hasNextLine()) < String line = scanner.nextLine(); //Scan the line for tokens try (Scanner rowScanner = new Scanner(line)) < rowScanner.useDelimiter(","); while (rowScanner.hasNext()) < System.out.print(scanner.next()); >> > > catch (FileNotFoundException e)

4. Using BufferedReader and String.split()

In this approach, we use BufferedReader to read the file line by line. Then the String.split() function is used to get tokens from the current line based on provided delimiter as the method parameter.

It is useful for small strings or small files.

Example 4: Splitting the CSV String or CSV File

In the given example, we are reading a file line by line. Then each line is split into tokens with a delimiter comma.

try(BufferedReader fileReader = new BufferedReader(new FileReader(«SampleCSVFile.csv»))) < String line = ""; //Read the file line by line while ((line = fileReader.readLine()) != null) < //Get all tokens available in line String[] tokens = line.split(","); //Verify tokens System.out.println(Arrays.toString(tokens)); >> catch (IOException e)

Reading a CSV file is possible with many approaches in Java. As Java does not directly have dedicated APIs for CSV handling, we can rely on open-source libraries such as SuperCSV that are very easy to use and highly configurable.

Источник

How to Convert CSV to TXT in Java? – Easy Method[2023]

How to Convert CSV to TXT in Java

To read data from the CSV file and write data to the TXT file, we have used the File I/O concept of Java. To convert CSV to TXT file, first, we need to read data line by line from CSV file and then we can convert line by line to a TXT file.

We have taken a sample CSV file to convert to TXT file. This file contains data of employees of different companies like Employee Name, Company Name, Designation and Salary.

You can also use the below CSV file to convert to a TXT file in Java. To use this CSV file, just download this file from below and save it to your system. You can use this file location of your System as the path in the program.

How to convert CSV to TXT in Java?

You can convert CSV to TXT in Java by using the File IO concept. We can use FileReader and BufferedReader classes to read data from the CSV file and then FileWriter class to write the same data to a TXT file.

 package cf.java.logical;  < public ; File file = FileReader fr = BufferedReader br = FileWriter writer =  ); > writer.write(  Output(TXT File): 

Explanation:

  • First, we have declared the file path of the CSV file as a String(String path = “C:/Satyajeet Nayak/Codingface/Demo.csv”;).
  • We have use File, FileReader, and BufferedReader classes to read data from CSV files.
  • We have used a demo TXT file(output.txt) to store employee data from the CSV file.
  • Then, we have used a while loop(while ((line = br.readLine()) != null)) to check that file should not be empty. When the file is not empty, by using the write( ) method of Writer class we can write each line of CSV file to TXT file.
  • Finally, the whole data of the CSV file will be converted to a TXT file.

Notepad Image:

Convert CSV to TXT in Java output file

Other Programmers Also Ask For:

  1. How to convert CSV file to TXT file in Java?
  2. How to convert CSV to TXT file?
  3. How to generate a TXT file from CSV file?

Источник

Читайте также:  Html таблица ввод данных
Оцените статью