我有一个数据集 csv 文件,包含大约 46000 个实例和 17 个属性。然后我提取列值并按 1 递增修改其值,现在我想要包含修改值的 csv 文件。我怎样才能得到...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileWriter;
//import com.csvreader.CsvWriter;
//import com.opencsv.CSVReader;
//import com.opencsv.CSVWriter;
//import au.com.bytecode.opencsv.CSVWriter;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
String filename ="bank-full.csv";
File file= new File(filename);
try {
Scanner inputStream = new Scanner(file);
inputStream.next();
while(inputStream.hasNext())
{
double abc;
String data= inputStream.next();
String[] values = data.split(";");
double balance= Double.parseDouble(values[11]);
balance=balance+1;
System.out.println(balance);
}
inputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
最佳答案
您已经拥有 String[] 值
中的值的字符串数组。那么为什么不将修改后的 balance
分配回 values[11]
,然后连接这些值并用分号粘合呢?
您可以尝试在System.out.println(balance);
之后添加此内容:
System.out.println(balance);
// replace original value with the modified balance
values[11] = String.valueOf(balance);
// iterate through the values and build a string out of them
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i < values.length - 1) {
// if it is not the last value, put a semicolon in between
sb.append(";");
}
}
// get the new string
String newData = sb.toString();
System.out.println(newData);
新值现在存储在字符串newData
中。只需将 newData
写入新的 .csv 文件即可。
关于java - 如何使用java修改特定数字列值后写入CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28294277/