CSV入力ファイルの読み取り、いくつかの単純な変換の実行、および書き込みを可能にする単純なAPIを誰かが推奨できますか?
簡単なグーグルは有望に見えるhttp://flatpack.sourceforge.net/を発見しました。
このAPIを使用する前に、他のユーザーが何を使用しているかを確認したいと思いました。
CSV入力ファイルの読み取り、いくつかの単純な変換の実行、および書き込みを可能にする単純なAPIを誰かが推奨できますか?
簡単なグーグルは有望に見えるhttp://flatpack.sourceforge.net/を発見しました。
このAPIを使用する前に、他のユーザーが何を使用しているかを確認したいと思いました。
回答:
Apache Common CSVを調べてください。
このライブラリは、標準のRFC 4180を含む、CSVのいくつかのバリエーションを読み書きします。また、タブ区切りファイルの読み取り/書き込みも行います。
過去にOpenCSVを使用したことがあります。
import au.com.bytecode.opencsv.CSVReader;
String fileName = "data.csv"; CSVReaderリーダー= new CSVReader(new FileReader(fileName));//最初の行がヘッダーの場合 String []ヘッダー= reader.readNext();
// nullを返すまでreader.readNextを繰り返します String [] line = reader.readNext();
別の質問への回答には他にもいくつかの選択肢がありました。
更新:この回答のコードはSuper CSV 1.52用です。Super CSV 2.4.0の更新されたコード例は、プロジェクトのWebサイトにあります。http: //super-csv.github.io/super-csv/index.html
SuperCSVプロジェクトは、CSVセルの解析と構造化された操作を直接サポートします。http://super-csv.github.io/super-csv/examples_reading.htmlから、たとえば、
クラスを与えられた
public class UserBean {
String username, password, street, town;
int zip;
public String getPassword() { return password; }
public String getStreet() { return street; }
public String getTown() { return town; }
public String getUsername() { return username; }
public int getZip() { return zip; }
public void setPassword(String password) { this.password = password; }
public void setStreet(String street) { this.street = street; }
public void setTown(String town) { this.town = town; }
public void setUsername(String username) { this.username = username; }
public void setZip(int zip) { this.zip = zip; }
}
ヘッダー付きのCSVファイルがあることを確認します。次の内容を想定しましょう
username, password, date, zip, town
Klaus, qwexyKiks, 17/1/2007, 1111, New York
Oufu, bobilop, 10/10/2007, 4555, New York
次に、UserBeanのインスタンスを作成し、次のコードを使用して、ファイルの2行目の値を設定できます。
class ReadingObjects {
public static void main(String[] args) throws Exception{
ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = inFile.getCSVHeader(true);
UserBean user;
while( (user = inFile.read(UserBean.class, header, processors)) != null) {
System.out.println(user.getZip());
}
} finally {
inFile.close();
}
}
}
次の「操作仕様」を使用
final CellProcessor[] processors = new CellProcessor[] {
new Unique(new StrMinMax(5, 20)),
new StrMinMax(8, 35),
new ParseDate("dd/MM/yyyy"),
new Optional(new ParseInt()),
null
};
CSV形式の説明を読むと、サードパーティのライブラリを使用する方が自分で書くよりも頭痛が少ないと感じます。
ウィキペディアには、10個または既知のライブラリがリストされています。
ある種のチェックリストを使用してリストされたライブラリを比較しました。OpenCSVは私に優勝者(YMMV)を出し、次の結果を得ました:
+ maven
+ maven - release version // had some cryptic issues at _Hudson_ with snapshot references => prefer to be on a safe side
+ code examples
+ open source // as in "can hack myself if needed"
+ understandable javadoc // as opposed to eg javadocs of _genjava gj-csv_
+ compact API // YAGNI (note *flatpack* seems to have much richer API than OpenCSV)
- reference to specification used // I really like it when people can explain what they're doing
- reference to _RFC 4180_ support // would qualify as simplest form of specification to me
- releases changelog // absence is quite a pity, given how simple it'd be to get with maven-changes-plugin // _flatpack_, for comparison, has quite helpful changelog
+ bug tracking
+ active // as in "can submit a bug and expect a fixed release soon"
+ positive feedback // Recommended By 51 users at sourceforge (as of now)
最後のエンタープライズアプリケーションでは、かなりの量のCSV(数か月前)を処理するために必要な作業を行いました。sourceforgeでSuperCSVを使用したところ、シンプルで堅牢で問題がないことがわかりました。
次の場所からcsvreader apiを使用してダウンロードできます。
http://sourceforge.net/projects/javacsv/files/JavaCsv/JavaCsv%202.1/javacsv2.1.zip/download
または
http://sourceforge.net/projects/javacsv/
次のコードを使用します。
/ ************ For Reading ***************/
import java.io.FileNotFoundException;
import java.io.IOException;
import com.csvreader.CsvReader;
public class CsvReaderExample {
public static void main(String[] args) {
try {
CsvReader products = new CsvReader("products.csv");
products.readHeaders();
while (products.readRecord())
{
String productID = products.get("ProductID");
String productName = products.get("ProductName");
String supplierID = products.get("SupplierID");
String categoryID = products.get("CategoryID");
String quantityPerUnit = products.get("QuantityPerUnit");
String unitPrice = products.get("UnitPrice");
String unitsInStock = products.get("UnitsInStock");
String unitsOnOrder = products.get("UnitsOnOrder");
String reorderLevel = products.get("ReorderLevel");
String discontinued = products.get("Discontinued");
// perform program logic here
System.out.println(productID + ":" + productName);
}
products.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
CSVファイルへの書き込み/追加
コード:
/************* For Writing ***************************/
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.csvreader.CsvWriter;
public class CsvWriterAppendExample {
public static void main(String[] args) {
String outputFile = "users.csv";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');
// if the file didn't already exist then we need to write out the header line
if (!alreadyExists)
{
csvOutput.write("id");
csvOutput.write("name");
csvOutput.endRecord();
}
// else assume that the file already has the correct header line
// write out a few records
csvOutput.write("1");
csvOutput.write("Bruce");
csvOutput.endRecord();
csvOutput.write("2");
csvOutput.write("John");
csvOutput.endRecord();
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
CSV / Excelユーティリティもあります。すべてのthosデータがテーブルのようなものであり、イテレータからデータを配信することを前提としています。
CSV形式は、StringTokenizerには十分に簡単に聞こえますが、さらに複雑になる可能性があります。ここドイツでは、セミコロンが区切り文字として使用され、区切り文字を含むセルはエスケープする必要があります。StringTokenizerでこれを簡単に処理することはできません。
Excelからcsvを読み取る場合は、いくつかの興味深いコーナーケースがあります。私はそれらすべてを思い出すことはできませんが、Apache commons csvはそれを正しく処理することができませんでした(たとえば、URLで)。
引用符、カンマ、スラッシュを使ってExcel出力をテストしてください。