I want to read a PSV file using java. Records in my PSV file has 4 columns. I want to read and output only the 3 and 4th column. What is the best way to do this.
Here is what I have:
BufferedReader PSVFile = new BufferedReader(new FileReader(fileName));
String dataRow = PSVFile.readLine();
while (dataRow != null)
{
String[] dataArray = dataRow.split("\n");
for (String item:dataArray)
{
String[] elements = item.split("|");
System.out.println(item);
}
System.out.println();
dataRow = PSVFile.readLine();
}
PSVFile.close();
System.out.println();
Based on @AljoshaBre suggestion Iam using CSVReader, doing this:
reader = new CSVReader(new FileReader(fileName),'|');
String [] nextLine;
while ((nextLine = reader.readNext()) != null)
{
System.out.println( nextLine[3] + nextLine[4]);
}
I am getting the desired output but then get an error:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 2
at Read_PSV.main(Read_PSV.java:20)
Line 20 is System.out.println( nextLine[3] + nextLine[4]);
OpenCSV is my weapon of choice.
This snippet will get you third and forth columns:
It will print
for this input:
test.psv