用 Java 读写

下面的示例显示了在没有任何第三方库的情况下读取和写入 csv 文件的方法。

写 CSV

public void writeToCsvFile(List<String[]> thingsToWrite, String separator, String fileName){
    try (FileWriter writer = new FileWriter(fileName)){
        for (String[] strings : thingsToWrite) {
            for (int i = 0; i < strings.length; i++) {
                writer.append(strings[i]);
                if(i < (strings.length-1))
                    writer.append(separator);
            }
            writer.append(System.lineSeparator());
        }
        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

读取 CSV

// Allows to define custom separator
public List<String[]> readFromCsvFile(String separator, String fileName){
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))){
        List<String[]> list = new ArrayList<>();
        String line = "";
        while((line = reader.readLine()) != null){
            String[] array = line.split(separator);
            list.add(array);
        }
        return list;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }  
}

还有一些预编译的第三方库提供了解析 csv 文件的便捷方法。以下是此类库的一些示例。

OpenCSV

OpenCSV 被认为非常易于使用,并在解析 CSV 文件时提供灵活的功能

/** Reading CSV **/
// Allows varied parameters through constructors to define quote character, number of lines to skip, etc.
try(CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), separator)){
        List<String[]> = reader.readAll();
        // Do something with the data
}

/** Writing CSV **/
List<String[]> listToWrite= //fetch the list of string array to write;
try(CSVWriter writer = new CSVWriter(new FileWriter(fileName), separator)){
    writer.writeAll(listToWrite);
    writer.flush();
}

/** Dumping database records to CSV **/
// Initialize CSVWriter and fetch resultSet from database ...
    writer.writeAll(resultSet, includeColumnNames); 

OpenCSV 还允许将记录直接绑定到 JavaBeans。有关详细信息,请参阅官方文档在这里

其他已知的库包括 SuperCSVCommonsCSV ,它们也提供了一些高级功能。有关更多信息,请参阅官方文档。