Java 용 CSV API [닫기]

누구나 CSV 입력 파일을 읽고, 간단한 변환을 한 다음, 쓸 수있는 간단한 API를 추천 할 수 있습니까?

빠른 Google이 http://flatpack.sourceforge.net/ 을 찾았습니다 .

이 API에 자신을 연결하기 전에 다른 사람들이 무엇을 사용하고 있는지 확인하고 싶었습니다.



답변

아파치 커먼즈 CSV

Apache Common CSV를 확인하십시오 .

이 라이브러리 는 표준 RFC 4180을 포함하여 몇 가지 변형 된 CSV를 읽고 씁니다 . 또한 탭으로 구분 된 파일을 읽거나 씁니다 .

  • 뛰어나다
  • InformixUnload
  • InformixUnloadCsv
  • MySQL
  • 신탁
  • PostgreSQLCsv
  • PostgreSQL 텍스트
  • RFC4180
  • TDF

답변

과거에는 OpenCSV 를 사용 했습니다 .

import au.com.bytecode.opencsv.CSVReader;

문자열 fileName = "data.csv";
CSVReader 리더 = 새로운 CSVReader (new FileReader (fileName));

// 첫 번째 줄이 머리글 인 경우 String [] 헤더 = reader.readNext ();
// null을 반환 할 때까지 reader.readNext를 반복합니다. String [] line = reader.readNext ();

다른 질문 에 대한 답변에는 다른 선택이있었습니다 .


답변

업데이트 : 이 답변의 코드는 Super CSV 1.52 용입니다. Super CSV 2.4.0의 업데이트 된 코드 예제는 프로젝트 웹 사이트에서 찾을 수 있습니다.
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의 인스턴스를 작성하고 다음 코드를 사용하여 파일의 두 번째 줄의 값으로 채울 수 있습니다.

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 형식 설명을 읽으면 타사 라이브러리를 사용하는 것이 직접 작성하는 것보다 두통이 적습니다.

Wikipedia에는 ​​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)


답변

우리는 JavaCSV를 사용 하며 꽤 잘 작동합니다.


답변

몇 달 전 주목할만한 양의 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();
        }

    }
}