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 Overflow
Top answer
1 of 4
8

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!

2 of 4
5

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();
    }
🌐
Aspose
products.aspose.com › aspose.total › java › update › csv
Update CSV Files using Java | products.aspose.com
November 24, 2025 - Aspose.Total for Java provides libraries and tools enabling developers to read, modify, and write data to CSV files. This capability allows tasks like editing, appending, and updating CSV content within Java applications, making it a versatile ...
🌐
Coderanch
coderanch.com › t › 559466 › java › Write-Update-CSV-files
Write and Update CSV files (Java in General forum at Coderanch)
November 21, 2011 - I'm blocked while updating CSV with new rows, Please check my code and let me know the way to complete this. ... First I'm creating 'temp' csv file and copying existing file data into temp file and adding new rows to temp file and rename temp file name with actual name.
🌐
Stack Overflow
stackoverflow.com › questions › 30174411 › java-editing-csv-files-specific-cells-reading-and-updating
Java editing CSV files specific cells. Reading and updating - Stack Overflow
public class OpenCsv { private ... updateCsvFile(String source, String destination) throws Exception{ CSVReader reader = new CSVReader(new FileReader(source),SEPARATOR); List<String[]> csvBody = reader.readAll(); csvBody.get(1)[2]...
🌐
Stack Abuse
stackabuse.com › reading-and-writing-csvs-in-java
Reading and Writing CSVs in Java
February 20, 2019 - There are several ways to read and write CSV files in Java, the simplest being using Core Java components.
🌐
Example Code
example-code.com › java › csv_update.asp
Java Update CSV File
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin · © 2000-2025 Chilkat Software, Inc...
Top answer
1 of 1
2

If you want to create a new file and have the same lines plus comment there, you can do it like this (using java.nio for file system access and java 8 iterations):

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        // the path to your source file as a String
        String fileLocation = "Y:\\our\\path\\to\\lain.csv";
        // the path to your source file as a Path object (java.nio)
        Path filePath = Paths.get(fileLocation);
        // a list of Strings for the new lines, those with a comment separated by |
        List<String> updatedLines = new ArrayList<String>();

        try {
            // read all the lines of the csv source file into a list
            List<String> lines = Files.readAllLines(filePath, StandardCharsets.ISO_8859_1);

            System.out.println("————————————————————————————————————————————————————————————————");

            // print each line just to see if everything is properly read (the java 8 way)
            lines.forEach(line -> {
                System.out.println(line);
            });

            System.out.println("————————————————————————————————————————————————————————————————");

            // add a comment to each line and store it in the updatedLines 
            lines.forEach(line -> {
                /*
                 * TODO add some line-depending comment creation logic here,
                 * this just adds "a comment" to every line
                 */
                updatedLines.add(line + "|" + "a comment");
            });

            // print the updated lines
            updatedLines.forEach(updatedLine -> {
                System.out.println(updatedLine);
            });

            System.out.println("————————————————————————————————————————————————————————————————");

            // create a new file
            String updatedFileLocation = "Y:\\our\\path\\to\\lain_updated.csv";
            Path updatedFilePath = Paths.get(updatedFileLocation);
            Files.createFile(updatedFilePath);

            // write the updated lines to a new csv file
            Files.write(updatedFilePath, updatedLines,
                    StandardOpenOption.TRUNCATE_EXISTING);

            // final check: read the new file and print its content:
            Files.readAllLines(updatedFilePath).forEach(writtenUpdatedLine -> {
                System.out.println(writtenUpdatedLine);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Find elsewhere
Top answer
1 of 3
2

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();
}
2 of 3
0

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();
            }
        }
    }
Top answer
1 of 2
1

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).

2 of 2
0
**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;
  } 
Top answer
1 of 1
2

Not how it works. Think of a disk: It's a bit like a giant, single-floor hotel with a few billion rooms.

Now imagine that in this hotel you have all the olympians signed in, and they're all in consecutive rooms, sorted on country and then name.

And then a new olympian signs in as a late arrival. You can't just 'update' your hotel and give this olympian a room. Nono, you have to tell about half of the olympians to move one room over to the right, to make room.

Disks are the same. If you want to 'overwrite in place' (say, swap one of the olympians out with another one, in disk terms: Change the value of an existing byte within a file with another value), that's possible, and you'd need to use java's RandomAccessFile and a few other rather more specialized classes to do so, it's not a common task.

But for the vast majority of file updates, you don't get to do it in terms of fixed sizing, and then the notion of 'update in place' is out the window, as far as the disk is concerned.

What you CAN do, however, is this somewhat common task, which ensures that other processes running on that hardware always observe consistent data:

Let's say the hotel is represented by a file on disk that just lists the name of the olympian on a line, and then the next olympian on the next line, and so forth.

To add a new olympian so that the rest of the system always gets a consistent view:

  • Make a new file named e.g. olympians.txt.new.123981329183 (that number is just randomly generated to avoid conflicts), and start copying the data over from the old file.
  • During the copy operation, 'fix' the file, as in, insert the new olympian in the right spot.
  • When you're done close the file, and then use Files.move() with the ATOMIC_MOVE flag, in order to ask java to ask the OS to rename olympians.txt.new.123981329183 to olympians.txt, in an atomic fashion: Any process that opens olympians.txt either opens the old file or the new file, and regardless of which one they got, they always get the complete view; it's not possible to see the new file but only halfway through, or what not.

In that model, as far as the harddisk is concerned, you have 2 utterly different files, but paths (filenames) are just pointers to a spot on the disk, that's all they are. As far as software running on that hardware is concerned, there is only ever one file, it is called olympians.txt, if you open it is it always complete and consistent. When new olympians show up, eventually opening that file will include their name, and it'll be in the right place.

Summary:

  • If you want to replace values without changing any sizes, this is technically possible but not in an atomic fashion, and requires specialized JDK classes, such as RandomAccessFile.
  • If you want to remove or add data (change sizes), what you want is, as far as the harddisk is concerned, impossible.
  • You can, however, make it look like there is just the one file that is always consistent and gets updated from time to time, copy the file over and rotate it back into the right name using java.nio.file.Files's move method, making sure you use the StandardCopyOperation.ATOMIC_MOVE flag.
🌐
Mkyong
mkyong.com › home › java › how to read and parse csv file in java
How to read and parse CSV file in Java - Mkyong.com
December 26, 2020 - Talks about CSV file parsing, RFC 4180, OpenCSV and Single class implementation examples to read and parse a CSV file.
🌐
Javatpoint
javatpoint.com › how-to-read-csv-file-in-java
Read CSV File in Java
How to Read CSV File in Java with oops, string, exceptions, multithreading, collections, jdbc, rmi, fundamentals, programs, swing, javafx, io streams, networking, sockets, classes, objects etc,
🌐
Rip Tutorial
riptutorial.com › reading and writing in java
csv Tutorial => Reading and writing in Java
try(CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), separator)){ List<String[]> = reader.readAll(); // Do something with the data } /** Writing CSV **/ List<String[]> listToWrite= //fetch the list of string array to write; try(CSVWriter writer = new CSVWriter(new FileWriter(fileName), separator)){ writer.writeAll(listToWrite); writer.flush(); } /** Dumping database records to CSV **/ // Initialize CSVWriter and fetch resultSet from database ... writer.writeAll(resultSet, includeColumnNames); OpenCSV also allowes binding the records directly to JavaBeans.
🌐
CodeJava
codejava.net › coding › java-code-example-to-insert-data-from-csv-to-database
Java code example to insert data from CSV to database
September 24, 2019 - Thank you, instructor" "Design Patterns in Java",Darshan Patel,2019-06-28 21:46:56,5.0,"Great Experience, I love this course" ...In this case, you should use an external CSV library to handle all of these complexities, such as SuperCSV (open source).The following program illustrates how to use SuperCSV library to read data from a CSV file, and use JDBC batch update to insert data into the database to get best performance.
🌐
TechVidvan
techvidvan.com › tutorials › read-csv-file-in-java
How to Read CSV file in Java - TechVidvan
July 1, 2020 - We use the CSVReader class to read a CSV file. The class CSVReader provides a constructor to parse a CSV file. ... 1: Create a class file with the name CSVReaderDemo and write the following code.
Top answer
1 of 2
1

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.

2 of 2
0

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