Java: CSV File Easy Read/Write
Asked Answered
P

5

8

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?

Pereira answered 9/1, 2013 at 1:14 Comment(1)
Not an answer to your question per se: do you know SuperCSV, an easy to use and versatile CSV reading-writing library that seriously facilitates the interaction with csv files.Cheesewood
S
19

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

Summerwood answered 9/1, 2013 at 1:23 Comment(1)
Well that's easily said, but how about their license in commercial application? Because aren't we all developing commercial applications...Sinter
C
1

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

Cembalo answered 9/1, 2013 at 1:37 Comment(0)
T
1

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

Tonne answered 13/2, 2017 at 7:42 Comment(1)
Better to post the source code here rather than images.Redwine
M
0

Add Dependencies

implementation 'com.opencsv:opencsv:4.6'

Add Below Code in onCreate()

InputStreamReader is = null;
        try {
              String path= "storage/emulated/0/Android/media/in.bioenabletech.imageProcessing/MLkit/countries_image_crop.csv";
            
             CSVReader reader = new CSVReader(new FileReader(path));
             String[] nextLine;
             int lineNumber = 0;
             while ((nextLine = reader.readNext()) != null) {
                lineNumber++;

                //print CSV file according to your column 1 means first column, 2 means 
                  second column
                Log.e(TAG, "onCreate: "+nextLine[2] );
            }
        }
        catch (Exception e)
        {
             Log.e(TAG, "onCreate: "+e );
        }
Melisma answered 28/4, 2021 at 7:18 Comment(0)
C
0

I solved it using

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-csv</artifactId>
        <version>2.8.6</version>
    </dependency>

and

  private static final CsvMapper mapper = new CsvMapper();
  public static <T> List<T> readCsvFile(MultipartFile file, Class<T> clazz) throws IOException {
    InputStream inputStream = file.getInputStream();
    CsvSchema schema = mapper.schemaFor(clazz).withHeader().withColumnReordering(true);
    ObjectReader reader = mapper.readerFor(clazz).with(schema);
    return reader.<T>readValues(inputStream).readAll();
}
Chinook answered 22/2, 2022 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.