end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

apache commons csv for javaで、文字コードを指定して読む

先程のエントリのおまけ。以下

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;


public class TestConvEncode3 {
    public static void main(String[] args) {
        String nowDir = new File(".").getAbsoluteFile().getParent();
        System.out.println("CURRENT DIR: " + nowDir);
        
        InputStreamReader isr0 = new InputStreamReader(System.in);
        
        String csvPath;
        try(BufferedReader br0 = new BufferedReader( isr0 ) ) {
            System.out.println("input csv file path below...");
            csvPath = br0.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        
        List<CSVRecord> recordList;
        
        try(BufferedReader br = 
            new BufferedReader(
                               new InputStreamReader(
//                                              new FileInputStream(new File(csvPath)),"MS932"))){
                                                     new FileInputStream(new File(csvPath)),"SJIS"))){
            CSVParser parse =
                CSVFormat
                .EXCEL                          // ExcelのCSV形式を指定
                .withIgnoreEmptyLines(true)     // 空行を無視する
                .withFirstRecordAsHeader()      // 最初の行をヘッダーとして読み飛ばす
                .withIgnoreSurroundingSpaces(true)  // 値をtrim
                .parse(br);
            
            recordList = parse.getRecords();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        
        for (CSVRecord record : recordList) {
            for(int i = 0; i< record.size(); i++) {
                System.out.println(record.get(i) );
            }
            System.out.println("");
        }
    }
}