Reputation: 852
Can anybody tell me how can i parse the file using open csv? I am trying from many days but i didnt get a result. Here is my code
package csv;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
import java.io.FileReader;
import csv.*;
import java.io.*;
public class CSVParser {
public static void main(String[] args) throws IOException,java.io.FileNotFoundException {
try{
CSVReader reader = new CSVReader(new FileReader("D:\\error.txt"));
String sLine = null;
String[] nextLine;
int count=0,flag=0;
nextLine=reader.readNext();
while( (nextLine!=null) )
{
count++;
System.out.println("count::: "+count + "and length is" +nextLine.length);
System.out.println("String:::"+nextLine[0]);
if ( (nextLine.length!= 9) ) {
flag=1;
break;
}
nextLine=reader.readNext();
}
System.out.println("No of lines:::"+count);
if(flag==1)
{
reader.close();
System.out.println("errror");
movefiles m= new movefiles();
m.move("D:\\error.txt");
}
else{
System.out.println("No error");
try{
while((nextLine=reader.readNext())!=null) {
String code = nextLine[0].toString();
String commodity = nextLine[1].toString();
float contract_price = Float.parseFloat(nextLine[2].toString());
float open_contract_vol = Float.parseFloat(nextLine[3].toString());
float open_contract_price = Float.parseFloat(nextLine[4].toString());
float unpriced_vol = Float.parseFloat(nextLine[5].toString());
float holdover_prod = Float.parseFloat(nextLine[6].toString());
String date = nextLine[7].toString();
String time = nextLine[8].toString();
System.out.println("Data From File is :::" + code +commodity +contract_price +open_contract_vol +open_contract_price +unpriced_vol +holdover_prod +date +time);
}}catch(Exception e)
{
e.printStackTrace();
System.err.println("here is error:::"+e.getMessage());
}
}
reader.close();
} catch(Exception e) {
e.printStackTrace();
System.err.println("error:::" +e.getMessage());
}
}
}
But problem is when i run this code even if my file contains one line it shows two lines and second line doesn't contain anything. I think it may contain white space. can anybody tell me why even if my file contain one line it is showing me 2 and how can i overcome it. How to read a single line at a time. pls help me i am new to csv for this i am using opencsv jar library
Upvotes: 0
Views: 3701
Reputation: 80603
Without seeing your input file its hard to tell. But in any case the first part of your code works as it should, iterating over the lines in the input file. But the second part of your code is questionable:
if(flag==1) {
reader.close();
System.out.println("errror");
movefiles m= new movefiles();
m.move("D:\\error.txt");
} else{
// ...
}
The else check is unnecessary, if there was no error on any of the lines (column count less than 9), then the first part of the code would have already iterated to the end of the file. You either want to:
Create a pastebin with your input file so we can verify there are no errors in it.
Upvotes: 2