updating specific cell csv file using java

前端 未结 5 955
悲哀的现实
悲哀的现实 2020-12-06 15:07

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 st

相关标签:
5条回答
  • 2020-12-06 15:41

    You're doing something like this:

      String line = readLineFromFile();
      line.replace(...);
    

    This is not editing the file, it's creating a new string from a line in the file.

    String instances are immutable, so the replace call you're making returns a new string it does not modify the original string.

    Either use a file stream that allows you to both read and write to the file - i.e. RandomAccessFile or (more simply) write to a new file then replace the old file with the new one

    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.

    0 讨论(0)
  • 2020-12-06 15:48

    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!

    0 讨论(0)
  • 2020-12-06 16:01

    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();
        }
    
    0 讨论(0)
  • 2020-12-06 16:05

    CSV file is just a file. It is not being changed if you are reading it. So, write your changes!

    You have 3 ways.

    1

    1. read line by line finding the cell you want to change.
    2. change the cell if needed and composite new version of current line.
    3. write the line into second file.
    4. 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.

    2

    Use RandomAccess file to write into specific place of the file.

    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.

    0 讨论(0)
  • 2020-12-06 16:05

    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

    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());
    }
    
    0 讨论(0)
提交回复
热议问题