須要jar包:javacsv-2.0.jarjava
讀操做編碼
// 讀取csv文件的內容 public static ArrayList<String> readCsv(String filepath) { File csv = new File(filepath); // CSV文件路徑 csv.setReadable(true);//設置可讀 csv.setWritable(true);//設置可寫 BufferedReader br = null; try { br = new BufferedReader(new FileReader(csv)); } catch (FileNotFoundException e) { e.printStackTrace(); } String line = ""; String everyLine = ""; ArrayList<String> allString = new ArrayList<>(); try { while ((line = br.readLine()) != null) // 讀取到的內容給line變量 { everyLine = line; System.out.println(everyLine); allString.add(everyLine); } System.out.println("csv表格中全部行數:" + allString.size()); } catch (IOException e) { e.printStackTrace(); } return allString; }
寫操做spa
public void writeCSV(String path) { String csvFilePath = path;
try { // 建立CSV寫對象 例如:CsvWriter(文件路徑,分隔符,編碼格式); CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("GBK")); // 寫內容 String[] headers = {"FileName","FileSize","FileMD5"}; csvWriter.writeRecord(headers); for(int i=0;i<writearraylist.size();i++){ String[] writeLine=writearraylist.get(i).split(","); System.out.println(writeLine); csvWriter.writeRecord(writeLine); } csvWriter.close(); System.out.println("--------CSV文件已經寫入--------"); } catch (IOException e) { e.printStackTrace(); } }