在Java中讀寫.csv檔案
如何讀取/一個名為OpenCSV的庫提供了用於從/向.CSV檔案讀寫資料的API。這裡解釋瞭如何使用Java程式讀取.csv檔案的內容。
Maven依賴
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
com.opencsv包的CSVReader類代表一個簡單的csv讀取器。例項化此類時,需要將表示要讀取檔案的Reader物件作為引數傳遞給其建構函式。它提供名為readAll()和readNext()的方法來讀取.csv檔案的內容。
使用readNext()方法
CSVReader類的readNext()方法讀取.csv檔案的下一行,並將其以字串陣列的形式返回。
示例
下面的Java程式演示瞭如何使用readNext()方法讀取.csv檔案的內容。
import java.io.FileReader;
import com.opencsv.CSVReader;
public class ReadFromCSV {
public static void main(String args[]) throws Exception {
//Instantiating the CSVReader class
CSVReader reader = new CSVReader(new FileReader("D://sample.csv"));
//Reading the contents of the csv file
StringBuffer buffer = new StringBuffer();
String line[];
while ((line = reader.readNext()) != null) {
for(int i = 0; i<line.length; i++) {
System.out.print(line[i]+" ");
}
System.out.println(" ");
}
}
}輸出
id name salary start_date dept 1 Rick 623.3 2012-01-01 IT 2 Dan 515.2 2013-09-23 Operations 3 Michelle 611 2014-11-15 IT 4 Ryan 729 2014-05-11 HR 5 Gary 843.25 2015-03-27 Finance 6 Nina 578 2013-05-21 IT 7 Simon 632.8 2013-07-30 Operations 8 Guru 722.5 2014-06-17 Finance
將資料寫入CSV檔案
com.opencsv包的CSVWriter類代表一個簡單的csv寫入器。例項化此類時,需要將表示要寫入資料的檔案的Writer物件作為引數傳遞給其建構函式。它提供名為writeAll()和writeNext()的方法來將資料寫入.csv檔案。
使用writeNext()方法 −
CSVWriter類的writeNext()方法將下一行寫入.csv檔案。
示例
下面的Java程式演示瞭如何使用writeNext()方法將資料寫入.csv檔案。
import java.io.FileWriter;
import com.opencsv.CSVWriter;
public class WritingToCSV {
public static void main(String args[]) throws Exception {
//Instantiating the CSVWriter class
CSVWriter writer = new CSVWriter(new FileWriter("D://output.csv"));
//Writing data to a csv file
String line1[] = {"id", "name", "salary", "start_date", "dept"};
String line2[] = {"1", "Krishna", "2548", "2012-01-01", "IT"};
String line3[] = {"2", "Vishnu", "4522", "2013-02-26", "Operations"};
String line4[] = {"3", "Raja", "3021", "2016-10-10", "HR"};
String line5[] = {"4", "Raghav", "6988", "2012-01-01", "IT"};
//Writing data to the csv file
writer.writeNext(line1);
writer.writeNext(line2);
writer.writeNext(line3);
writer.writeNext(line4);
//Flushing data from writer to file
writer.flush();
System.out.println("Data entered");
}
}輸出
Data entered
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP