Although using the Apache CSV library, as mentioned in @ Minjun.Y, is fine, I try to provide a solution that is closer to your code, and maybe it will be easier for you:
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class CsvParser { public static void main(String[] args) { String fileName= "read_ex.csv"; File file= new File(fileName);
Skip it step by step:
I added 3 more imports: ArrayList , Arrays and List - you will soon see that they are good. They are all taken from the java.util library, the standard library available with every JDK.
Each class name in Java starts with a capital letter (by convention - it will be built with a small letter, but you should get used to this convention) - I "fixed" this in your code.
I added a 2-dimensional array List<List<String>> lines = new ArrayList<>() . This may seem a bit confusing at first, but that means that we are creating the lines variable that contains the results of our parsing. The syntax of List<String> means that we have a generic List type that has a parameter of type String - in other words: a list of strings. The whole List<List<String>> means that we have a list of string lists, a 2-dimensional string array.
Using lines.add(Arrays.asList(values)) in your while we can add the lines you analyzed in this two-dimensional array. Arrays.asList(values) converts the String[] array to List , because we need it to be compatible with our type List<List<...>> . This allows your lines to have a variable length.
The last lines that I added just print the contents of the two-dimensional array and should give you a good example of how to access the values ββin this array. If you need more help for this design, check out the foreach loop documentation .
Given this as an input file ( read_ex.csv ):
value_1-1,value_1-2,value_1-3,value_1-4 value_2-1,value_2-2,value_2-3,value_2-4 value_3-1,value_3-2,value_3-3,value_3-4 value_4-1,value_4-2,value_4-3,value_4-4 value_5-1,value_5-2,value_5-3,value_5-4
The program will print the following output:
Line 1 Column 1: value_1-1 Line 1 Column 2: value_1-2 Line 1 Column 3: value_1-3 Line 1 Column 4: value_1-4 Line 2 Column 1: value_2-1 Line 2 Column 2: value_2-2 Line 2 Column 3: value_2-3 Line 2 Column 4: value_2-4 Line 3 Column 1: value_3-1 Line 3 Column 2: value_3-2 Line 3 Column 3: value_3-3 Line 3 Column 4: value_3-4 Line 4 Column 1: value_4-1 Line 4 Column 2: value_4-2 Line 4 Column 3: value_4-3 Line 4 Column 4: value_4-4 Line 5 Column 1: value_5-1 Line 5 Column 2: value_5-2 Line 5 Column 3: value_5-3 Line 5 Column 4: value_5-4
Hope this helps :)
source share