Java:CSV 文件易于读​​/写 [英] Java: CSV File Easy Read/Write

查看:35
本文介绍了Java:CSV 文件易于读​​/写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要快速访问 CSV 逗号分隔电子表格文件的程序.到目前为止,我已经能够使用 BufferedReader 轻松读取它.但是,现在我希望能够编辑它读取的数据,然后将其导出回 CSV.

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.

电子表格包含姓名、电话号码、电子邮件地址等.程序会列出每个人的数据,当您点击它们时,它会显示一个包含更详细信息的页面,这些信息也是从 CSV 中提取的.在该页面上,您可以编辑数据,我希望能够单击保存更改"按钮,然后将数据导出回 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.

我不太熟悉使用 BufferedWriter,或者我应该使用的任何东西.

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

我开始做的是创建一个名为 FileIO 的自定义类.它包含一个 BufferedReader 和一个 BufferedWriter.到目前为止,它有一个返回 bufferedReader.readLine() 的方法,称为 read().现在我想要一个叫做 write(String line) 的函数.

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?

推荐答案

与其重新发明轮子,不如看看 OpenCSV 支持读取和写入 CSV 文件.以下是阅读和阅读的示例写作

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

这篇关于Java:CSV 文件易于读​​/写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆