CSV converter Learn programming Java

Lesson:

File Management


Exercise:

CSV converter


Objetive:

The CSV ("Comma Separated Values") is an exchange format used by many spreadsheet and database management systems. It consists of a series of comma-separated values enclosed in quotation marks, although there are variants that do not use quotes or use semicolons as separators. Often, the values are not enclosed in quotes. An example file would be:

"John", "López Pérez," "Alicante", 25
"Antonio", "Pérez López", "Madrid", 27

You should create a program that reads a CSV file as shown above, with four data blocks (the first three are text and the last one is numeric), each of which is on a separate line. The program should generate a text file where each entry contains a line like this:

John
Pérez López
Alicante
25
Antonio
Pérez López
Madrid
27


Code:

package ReaderCSV;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		System.out.println("CSV READER");
		System.out.println("--------------------------------------");
		System.out.print("Enter name of file .csv: ");

		String nameFile = new Scanner(System.in).nextLine();
		java.io.InputStreamReader myfile;
		String cadena;
		int position;

		try
		{
			myfile = new java.io.InputStreamReader(nameFile, System.Text.Encoding.Default);
			String line;
			do
			{
				line = myfile.ReadLine();
				if ((line != null) && (!line.equals("")))
				{
					try
					{
						line = line.replace("\"", "");

						position = line.indexOf(';');
						cadena = line.substring(0, position);
						line = tangible.StringHelper.remove(line, 0, position + 1);
						System.out.println(cadena + "\n");

						position = line.indexOf(';');
						cadena = line.substring(0, position);
						line = tangible.StringHelper.remove(line, 0, position + 1);
						System.out.println(cadena + "\n");

						position = line.indexOf(';');
						cadena = line.substring(0, position);
						line = tangible.StringHelper.remove(line, 0, position + 1);
						System.out.println(cadena + "\n");

						cadena = line.substring(0);
						System.out.println(cadena + "\n");
					}
					catch (RuntimeException e)
					{
						System.out.println("Error !!! " + e.getMessage());
					}
				}
			} while (line != null);
		}
		catch (RuntimeException e)
		{
			System.out.println("Error !!!" + e.getMessage());
		}
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.