Java: CSV File Easy Read/Write

35,536

Solution 1

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

Solution 2

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: enter image description here

Unit test code: enter image description here

Solution 3

The spreadsheet contains names, phone numbers, email addresses, etc. And the program lists everyone's data, and when you click on them it brings up a page with more detailed information, also pulled from the CSV. On that page you can edit the data, and I want to be able to click a "Save Changes" button, then export the data back to its appropriate line in the CSV--or delete the old one, and append the new.

The content of a file is a sequence of bytes. CSV is a text based file format, i.e. the sequence of byte is interpreted as a sequence of characters, where newlines are delimited by special newline characters.

Consequently, if the length of a line increases, the characters of all following lines need to be moved to make room for the new characters. Likewise, to delete a line you must move the later characters to fill the gap. That is, you can not update a line in a csv (at least not when changing its length) without rewriting all following lines in the file. For simplicity, I'd rewrite the entire file.

Since you already have code to write and read the CSV file, adapting it should be straightforward. But before you do that, it might be worth asking yourself if you're using the right tool for the job. If the goal is to keep a list of records, and edit individual records in a form, programs such as Microsoft Access or whatever the Open Office equivalent is called might be a more natural fit. If you UI needs go beyond what these programs provide, using a relational database to keep your data is probably a better fit (more efficient and flexible than a CSV).

Share:
35,536
Rich Young
Author by

Rich Young

Updated on April 28, 2021

Comments

  • Rich Young
    Rich Young about 3 years

    I'm working on a program that requires quick access to a CSV comma-delimited spreadsheet file. So far I've been able to read from it easily using a BufferedReader. However, now I want to be able to edit the data it reads, then export it BACK to the CSV.

    The spreadsheet contains names, phone numbers, email addresses, etc. And the program lists everyone's data, and when you click on them it brings up a page with more detailed information, also pulled from the CSV. On that page you can edit the data, and I want to be able to click a "Save Changes" button, then export the data back to its appropriate line in the CSV--or delete the old one, and append the new.

    I'm not very familiar with using a BufferedWriter, or whatever it is I should be using.

    What I started to do is create a custom class called FileIO. It contains both a BufferedReader and a BufferedWriter. So far it has a method that returns bufferedReader.readLine(), called read(). Now I want a function called write(String line).

    public static class FileIO {
        BufferedReader read;
        BufferedWriter write;
    
        public FileIO (String file) throws MalformedURLException, IOException {
            read = new BufferedReader(new InputStreamReader (getUrl(file).openStream()));
            write = new BufferedWriter (new FileWriter (file));
        }
    
        public static URL getUrl (String file) throws IOException {
            return //new URL (fileServer + file).openStream()));
                    FileIO.class.getResource(file);
        }
    
        public String read () throws IOException {
            return read.readLine();
        }
    
        public void write (String line) {
            String [] data = line.split("\\|");
            String firstName = data[0];
    
            // int lineNum = findLineThatStartsWith(firstName);
            // write.writeLine(lineNum, line);
        }
    };
    

    I'm hoping somebody has an idea as to how I can do this?

  • Fico
    Fico about 9 years
    Well that's easily said, but how about their license in commercial application? Because aren't we all developing commercial applications...
  • Basil Bourque
    Basil Bourque over 5 years
    Better to post the source code here rather than images.