使用 Java 處理 CSV 檔案


首先必須安裝 OpenCSV,它是 Java 的一個解析庫。該依賴項必須在 maven 專案的 pom.xml 檔案中提及。之後,可以使用以下程式碼。

示例

import java.io.FileReader;
import java.io.*;
public class Demo{
   public static void readDataLineByLine(String file){
      try{
         FileReader my_filereader = new FileReader(file);
         CSVReader csvReader = new CSVReader(my_filereader);
         String[] nextRecord;
         while ((nextRecord = csvReader.readNext()) != null){
            for (String cell : nextRecord){
               System.out.print(Output + "\t");
            }
            System.out.println();
         }
      }
      catch (Exception e){
         e.printStackTrace();
      }
   }
}

輸出

Prints data in a csv file line by line

一個名為 Demo 的類包含一個名為‘readDataLineByLine’的函式,它將檔案作為引數。建立了一個 FileReader 例項和一個 CSVReader 例項,該例項讀取 CSV 檔案中的元素。逐行讀取每一行並在螢幕上顯示。這是在 try 塊中編寫的,並且異常(如果有)將在‘catch’塊中捕獲。

更新於:17-Aug-2020

308 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.