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
303 views
in Technique[技术] by (71.8m points)

java - what is the best way to edit csv file

I have a incomplete csv file that needs to be accurately updated, so there is csv file like this :

one,two,three,four,five,six,seven,eight,nine,ten //This is a line(String)

Naturally the file is far more complex but in this format, here is what I want to do insert new-word,new-word1, new-word3 or n words between seven and eight(or any range). How can I do that?

Pseudo-code,code or example would be great, I don't have a clue how to even start.

UPDATE:

Maybe I should convert this to array or some kind of datastructure. Then insert new item at the certain position, shift the rest of the content right and do that for each insertion.

I don't know if is right way to go or how to begin programming it

UPDATE II:

Maybe read in csv in the list, split list into two lists, first one ending with seven. Then add n words to first list and join two lists at the end? also don't know how to program this

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Take a look at OpenCSV.

UPDATE: Here's some (barely) pseudocode to give a general idea of how you would use OpenCSV for this:

CSVReader reader = new CSVReader(new FileReader("old.csv"));
CSVWriter writer = new CSVWriter(new FileWriter("new.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    List<String> lineAsList = new ArrayList<String>(Arrays.asList(nextLine));
    // Add stuff using linesAsList.add(index, newValue) as many times as you need.
    writer.writeNext(lineAsList.toArray());
}

Hat-tip: @Mark Peters who points out that you can't update the results of Arrays.asList


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

...