使用java更新特定的单元格csv文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4397907/
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
updating specific cell csv file using java
提问by JavaBabyGirl
Hi i have a small problem and think i'm just not getting the correct syntax on one line of code. basically, i can write into my csv file and find a specific record using string tokenizer but it is not updating/editing the specified cells of that record. the record remains the same. please help....
嗨,我有一个小问题,我想我只是没有在一行代码中获得正确的语法。基本上,我可以写入我的 csv 文件并使用字符串标记器查找特定记录,但它不会更新/编辑该记录的指定单元格。记录保持不变。请帮忙....
回答by AlexR
CSV file is just a file. It is not being changed if you are reading it. So, write your changes!
CSV 文件只是一个文件。如果你正在阅读它,它不会被改变。所以,写下你的改变!
You have 3 ways.
你有3种方法。
1
1
- read line by line finding the cell you want to change.
- change the cell if needed and composite new version of current line.
- write the line into second file.
- when you finished you have the source file and the result file. Now if you want you can remove the source file and rename the result file to source.
- 逐行阅读,找到要更改的单元格。
- 如果需要,更改单元格并合成当前行的新版本。
- 将该行写入第二个文件。
- 完成后,您将获得源文件和结果文件。现在,如果您愿意,您可以删除源文件并将结果文件重命名为 source。
2
2
Use RandomAccess file to write into specific place of the file.
使用 RandomAccess 文件写入文件的特定位置。
3
3
Use one of available implementations of CSV parser (e.g. http://commons.apache.org/sandbox/csv/) It already supports what you need and exposes high level API.
使用 CSV 解析器的一种可用实现(例如http://commons.apache.org/sandbox/csv/)它已经支持您需要的内容并公开高级 API。
回答by daveb
You're doing something like this:
你正在做这样的事情:
String line = readLineFromFile();
line.replace(...);
This is not editing the file, it's creating a new stringfrom a line in the file.
这不是编辑文件,而是从文件中的一行创建一个新字符串。
String
instances are immutable, so the replace
call you're making returns a newstring it does not modifythe original string.
String
实例是不可变的,因此replace
您进行的调用会返回一个新字符串,它不会修改原始字符串。
Either use a file stream that allows you to both read and write to the file - i.e. RandomAccessFileor (more simply) write to a new file then replace the old file with the new one
要么使用允许您读取和写入文件的文件流 - 即RandomAccessFile或(更简单地)写入新文件,然后用新文件替换旧文件
In psuedo code:
在伪代码中:
for (String line : inputFile) {
String [] processedLine = processLine(line);
outputFile.writeLine(join(processedLine, ","));
}
private String[] processLine(String line) {
String [] cells = line.split(","); // note this is not sufficient for correct csv parsing.
for (int i = 0; i < cells.length; i++) {
if (wantToEditCell(cells[i])) {
cells[i] = "new cell value";
}
}
return cells;
}
Also, please take a look at this question. There are libraries to help you deal with csv.
另外,请看看这个问题。有一些库可以帮助您处理 csv。
回答by JavaBabyGirl
ok i am doing something like this. i can access the csv record pointed to by tokens but it does not update i think incorrect syntax
好的,我正在做这样的事情。我可以访问令牌指向的 csv 记录,但它不会更新我认为语法不正确
private static void ChangeRecord(String sFileName) {
// TODO Auto-generated method stub
try {
BufferedReader r = new BufferedReader(
new InputStreamReader(
new FileInputStream(sFileName)));
String line;
while((line = r.readLine()) != null){
String tokens[] = line.split(",");
String Surname = tokens[1];
String network= tokens[2];
String city= tokens[4];
StringTokenizer StrTok = new StringTokenizer(party);
if(StrTok.hasMoreTokens()){
if ((city.equals("New York"))&&(Surname.equals("Smith"))){
String Lovely= "waterloo";
//this line is the one that i think is failing
line.replace(network, Lovely);
System.out.println(line);
}
}
}
r.close();
} catch(IOException e) {
System.out.println(" There was an Error Reading the file. " + e.getMessage());
}
回答by Chetan Aher
I have used http://opencsv.sourceforge.netin java
我在 java 中使用过http://opencsv.sourceforge.net
Hi, This is the code to update CSV by specifying row and column
嗨,这是通过指定行和列来更新 CSV 的代码
/**
* Update CSV by row and column
*
* @param fileToUpdate CSV file path to update e.g. D:\chetan\test.csv
* @param replace Replacement for your cell value
* @param row Row for which need to update
* @param col Column for which you need to update
* @throws IOException
*/
public static void updateCSV(String fileToUpdate, String replace,
int row, int col) throws IOException {
File inputFile = new File(fileToUpdate);
// Read existing file
CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
List<String[]> csvBody = reader.readAll();
// get CSV row column and replace with by using row and column
csvBody.get(row)[col] = replace;
reader.close();
// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}
This solution worked for me, Cheers!
这个解决方案对我有用,干杯!
回答by mannedear
I used the below code where I will replace a string with another and it worked exactly the way I needed:
我使用了下面的代码,我将用另一个字符串替换一个字符串,它完全按照我需要的方式工作:
public static void updateCSV(String fileToUpdate) throws IOException {
File inputFile = new File(fileToUpdate);
// Read existing file
CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
List<String[]> csvBody = reader.readAll();
// get CSV row column and replace with by using row and column
for(int i=0; i<csvBody.size(); i++){
String[] strArray = csvBody.get(i);
for(int j=0; j<strArray.length; j++){
if(strArray[j].equalsIgnoreCase("Update_date")){ //String to be replaced
csvBody.get(i)[j] = "Updated_date"; //Target replacement
}
}
}
reader.close();
// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}