1. 程式人生 > >Java使用opencsv 讀取csv檔案

Java使用opencsv 讀取csv檔案

maven依賴

<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
 <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>3.3</version>
</dependency>

程式碼案例,讀取csv全部檔案

public void readCsv(String path) {
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(new File(path)));
            CSVReader csvReader = new CSVReader(new InputStreamReader(in, "UTF-8"), CSVParser.DEFAULT_SEPARATOR,
                    CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, 0);
            String[] strs;
             while ((strs = csvReader.readNext()) != null) {
               System.out.println(Arrays.deepToString(strs));
            }

            csvReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

對csv檔案 其中一列進行讀取,列是以0為計數開始

public void readCsv(String path) {
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(new File(path)));
            CSVReader csvReader = new CSVReader(new InputStreamReader(in, "UTF-8"), CSVParser.DEFAULT_SEPARATOR,
                    CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, 0);
            String[] strs;
            // while ((strs = csvReader.readNext()) != null) {
            //    System.out.println(Arrays.deepToString(strs));
            //}

            while ((strs = csvReader.readNext()) != null) {
                 System.out.println(strs[0]);
            }

            csvReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

呼叫,傳入檔案路徑執行即可

public static void main(String[] args) throws IOException {
        test2 test=new test2();
        test.readCsv("D:\\test.csv");
    }