Reputation: 2760
I have a csv file in which I am able to insert the header for the first run, but when I again write the file the program is creating the header again. Is there a way to check if csv file has a header and if yes then to skip it?
Upvotes: 0
Views: 8920
Reputation: 974
Are you simply appending the records to the existing file and in which case the program is appending the header after the prior write?
Can you simply check if the file exists and if it does and is not size zero, assume the header is already present?
Upvotes: 0
Reputation: 4793
You would have to read the first line and test if the first column matches the column header you expect. Since your code inserts the header, I'm assuming it knows what the header should look like. You can use this same variable in your header check. Something like:
String HEADER = "column1,column2,column3";
String COLUMN1 = HEADER.substring(0,HEADER.indexOf(",")+1); //Or just set it to "column1", but that would be violating the DRY principle!
//...Get line1, column1 from the file you are reading
if(!line1Column1.equals(COLUMN1))
{
out.write(HEADER);
}
// Print rows of data...
Upvotes: 4
Reputation: 38168
If you inserted the header, couldn't you make it start, for instance with a dash (#) and if present not to write again ?
Regards, Stéphane
Upvotes: 1
Reputation: 17472
Are you using any framework to do that or you are doing it yourself.. A code snippet would help... or you can put a Boolean flag to check or hard match the first line with the standard header code to check it...
Upvotes: 1