I have used http://opencsv.sourceforge.net in java
Hi, This is the code to update CSV by specifying row and column
/**
* 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!
Answer from Chetan Aher on Stack OverflowI have used http://opencsv.sourceforge.net in java
Hi, This is the code to update CSV by specifying row and column
/**
* 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!
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();
}
Videos
Rather than reinventing the wheel you could have a look at OpenCSV which supports reading and writing of CSV files. Here are examples of reading & writing
Please consider Apache commons csv. To fast understand the api, there are four important classes:
CSVFormat
Specifies the format of a CSV file and parses input.
CSVParser
Parses CSV files according to the specified format.
CSVPrinter
Prints values in a CSV format.
CSVRecord
A CSV record parsed from a CSV file.
Code Example:

Unit test code:

Create a class to store the header values, and store it in the list. Iterate over the list to save the results.
The currently used map can only store 2 values (which it is storing the header value (name its corresponding value)
map.put(d[0], d[1]); here d[0] will be header1 and d[1] will be 4 (but we want only 4 from here)
class Headervalues {
String[] header = new String[3];
}
public void readLogFile() throws Exception
{
List<HeaderValues> list = new ArrayList<>();
String currentLine = "";
BufferedReader reader = new BufferedReader(new FileReader(file(false)));
while ((currentLine = reader.readLine()) != null)
{
if (currentLine.contains("2016") && currentLine.contains("helloworld"))
{
String nextBlock = replaceAll(currentLine.substring(22, currentLine.length());
String[] data = nextBlock.split(";");
HeaderValues headerValues = new HeaderValues();
//Assuming data.length will always be 3.
for (int i = 0, max = data.length; i < max; i++)
{
String[] d = data[i].split("=");
//Assuming split will always have size 2
headerValues.header[i] = d[1];
}
list.add(headerValues)
}
}
}
reader.close();
}
public void writeContentToCsv() throws Exception
{
FileWriter writer = new FileWriter(".../file_new.csv");
for (HeaderValues value : headerValues)
{
writer.append(value.header[0]).append(";").append(value.header[1]).append(";").append(value.header[2]);
}
writer.close();
}
For writing to CSV
public void writeCSV() {
// Delimiter used in CSV file
private static final String NEW_LINE_SEPARATOR = "\n";
// CSV file header
private static final Object[] FILE_HEADER = { "Empoyee Name","Empoyee Code", "In Time", "Out Time", "Duration", "Is Working Day" };
String fileName = "fileName.csv");
List<Objects> objects = new ArrayList<Objects>();
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
// Create the CSVFormat object with "\n" as a record delimiter
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
try {
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);
// Write a new student object list to the CSV file
for (Object object : objects) {
List<String> record = new ArrayList<String>();
record.add(object.getValue1().toString());
record.add(object.getValue2().toString());
record.add(object.getValue3().toString());
csvFilePrinter.printRecord(record);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java.nio.file package now contains the Watch Service API. This, effectively:
This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed.
See reference here.
Oh! This API is only available from JDK 7 (onwards).
**OpenCsv is a best way to read csv file in java.
if your are using maven then you can use below dependency or download it's jar from web.**
@SuppressWarnings({"rawtypes", "unchecked"})
public void readCsvFile() {
CSVReader csvReader;
CsvToBean csv;
File fileEntry;
try {
fileEntry = new File("path of your file");
csv = new CsvToBean();
csvReader = new CSVReader(new FileReader(fileEntry), ',', '"', 1);
List list = csv.parse(setColumMapping(), csvReader);
//List of LabReportSampleData class
} catch (IOException e) {
e.printStackTrace();
}
}
//Below function is used to map the your csv file to your mapping object.
//columns String array: The value inside your csv file. means 0 index map with degree variable in your mapping class.
@SuppressWarnings({"rawtypes", "unchecked"})
private static ColumnPositionMappingStrategy setColumMapping() {
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(LabReportSampleData.class);
String[] columns =
new String[] {"degree", "radian", "shearStress", "shearingStrain", "sourceUnit"};
strategy.setColumnMapping(columns);
return strategy;
}
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
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
The task aims to replace certain data in a database table with corresponding values in a CSV file. To use Java directly for doing this requires loading the CSV file to the database and store it as a temporary table. That’s a hassle.
It is easy to do this using Java’s open-source package SPL. You just need one line of code:
| A | |
|---|---|
| 1 | =RDB.update@u(file("update_info.csv").import@ct(),infotable,link_name,title,browser_title) |
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as update.splx and invoke it in Java as you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con = DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call update ()");
st.execute();
…
Or execute the SPL string within a Java program as we execute a SQL statement:
…
st = con.prepareStatement("==RDB.update@u(file(\"update_info.csv\").import@ct(),
infotable,link_name,title,browser_title)");
st.execute();
…
View SPL source code.
Try this code. Using BufferedReader to read file and loop every line then every column.
String path = "file.csv";
String line = "";
String splitBy = ",";
try {
// parsing a CSV file into BufferedReader
BufferedReader br = new BufferedReader(new FileReader(path));
// read file line by line
while ((line = br.readLine()) != null) // returns a Boolean value
{
// spilt column values by comma
String[] row = line.split(splitBy); // use comma as separator
// print every column value
for (int i = 0; i < row.length; i++)
System.out.println(row[i]);
}
} catch (IOException e) {
e.printStackTrace();
}
I modified a bit from this web site: https://www.javatpoint.com/how-to-read-csv-file-in-java