Search code examples
javaopencsv

OpenCSV does not write all records


I have written a method in Java for updating a text file delimited by tab. I'm using the opencsv library. First I'm reading in the existing file, then I change the values of some columns and then I overwrite the file. I'm running Windows 7. The problem is now that not everything gets written to the file. Even if I don't change any value and just overwrite the file, not all records are written.

My code is the following. What is wrong with it?

 private void csvWrite(int[] boundary, String filename, int answerCount) {
        CSVReader csvReader = null;
        List<String[]> csvBody = null;
        try {
            csvReader = new CSVReader(new FileReader(PATH + FILE),'\t');
            csvBody = csvReader.readAll();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Search for the file
        int count = 0;
        for (String[] str : csvBody) {
            if (str[0].equals(filename)) {
                // found
                csvBody.get(count)[POS_START_INDEX+answerCount-2] = Arrays.toString(boundary);
                break;
            }
            count++;
        }

        try {
            csvReader.close();
            CSVWriter writer = new CSVWriter(new FileWriter(PATH + FILE),'\t');
            writer.writeAll(csvBody);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Solution

  • I came across the same issue. For me, it was because I was not properly closing all the readers and writers. Got resolved after implementing autocloseable:

        private File writeToTempFile(File file) throws IOException {
        File tempFile = new File("/var/tmp/newcsv.csv");
        tempFile.createNewFile();
        try(FileReader fileReader = new FileReader(file);
        CSVReader csvReader = new CSVReaderBuilder(fileReader).withSkipLines(4).build();
        FileWriter outputFileWriter = new FileWriter(tempFile);
            CSVWriter writer = new CSVWriter(outputFileWriter, CSVWriter.DEFAULT_SEPARATOR,
                    CSVWriter.NO_QUOTE_CHARACTER,
                    CSVWriter.NO_ESCAPE_CHARACTER,
                    CSVWriter.DEFAULT_LINE_END);){
            writer.writeAll(csvReader.readAll());
        }catch (Exception e){
    
        }
        return tempFile;
    }