i have a dataset csv file having around 46000 instance and 17 attributes.. then i extract on of the column values and modify its value by incremented by 1 now i want csv file with modified values.how can i get....
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);
}
}
You already have a string array of the values in String[] values
. So why not assign back the modified balance
to values[11]
and then join the values, glued with a semicolon?
You can try adding this after 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);
The new values are now stored in the string newData
. Just write newData
to a new .csv file.