java 编辑 csv 文件的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3110786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what is the best way to edit csv file
提问by Gandalf StormCrow
I have a incomplete csv file that needs to be accurately updated, so there is csv file like this :
我有一个不完整的 csv 文件需要准确更新,所以有这样的 csv 文件:
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-word3or n words between seven and eight(or any range). How can I do that?
自然,该文件要复杂得多,但在这种格式中,这是我想要插入的new-word,new-word1, new-word3或介于 7 到 8 个(或任何范围)之间的 n 个单词。我怎样才能做到这一点?
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
也许在列表中读取csv,将列表分成两个列表,第一个以七结尾。然后在第一个列表中添加 n 个单词并在最后加入两个列表?也不知道怎么编程
采纳答案by Hank Gay
Take a look at OpenCSV.
看看OpenCSV。
UPDATE: Here's some (barely) pseudocode to give a general idea of how you would use OpenCSV for this:
更新:这里有一些(几乎没有)伪代码,可以大致了解如何为此使用 OpenCSV:
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
帽子提示:@Mark Peters 指出您无法更新结果 Arrays.asList
回答by Peter Tillemans
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
这将在该行的第 7 项之后插入 newWords
回答by Marcus Adams
I'd parse it into a collection, add your items, then render it back out to a csv.
我会将它解析为一个集合,添加您的项目,然后将其渲染回 csv。

