Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to edit csv file

Tags:

java

csv

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

like image 797
Gandalf StormCrow Avatar asked Jun 24 '10 14:06

Gandalf StormCrow


2 Answers

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

like image 188
Hank Gay Avatar answered Nov 15 '22 14:11

Hank Gay


This pseudo-like code might help :

List values = Arrays.asList(line.split(",\s*"));
List newWords = Arrays.aList(newWordsLine.split(",\s*"));

values.addAll(7,newWords);

StringBuffer buf = new StringBuffer(values.get(0));
for(v : values.subList(1,values.size()) {
    buf.append(",",v);
}
return buf.toString();

this will insert the newWords after the 7th item on the line

like image 29
Peter Tillemans Avatar answered Nov 15 '22 14:11

Peter Tillemans