Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

java:how to check if csv file has header

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...