用 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。有關詳細資訊,請參閱官方文件在這裡 。
其他已知的庫包括 SuperCSV 和 CommonsCSV ,它們也提供了一些高階功能。有關更多資訊,請參閱官方文件。