简体   繁体   中英

Java: CSV File Easy Read/Write

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?

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

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: 在此处输入图片说明

Unit test code: 在此处输入图片说明

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

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 );
        }

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM