需要jar包:javacsv-2.0.jar
讀操作
// 讀取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;}</span></pre>
寫操作
public void writeCSV(String path) { String csvFilePath = path;
try {</span><span style="color: #008000">//</span><span style="color: #008000"> 創建CSV寫對象 例如:CsvWriter(文件路徑,分隔符,編碼格式);</span> CsvWriter csvWriter = <span style="color: #0000ff">new</span> CsvWriter(csvFilePath, ',', Charset.forName("GBK"<span style="color: #000000">)); </span><span style="color: #008000">//</span><span style="color: #008000"> 寫內容</span> String[] headers = {"FileName","FileSize","FileMD5"<span style="color: #000000">}; csvWriter.writeRecord(headers); </span><span style="color: #0000ff">for</span>(<span style="color: #0000ff">int</span> i=0;i<writearraylist.size();i++<span style="color: #000000">){ String[] writeLine</span>=writearraylist.get(i).split(","<span style="color: #000000">); System.out.println(writeLine); csvWriter.writeRecord(writeLine); } csvWriter.close(); System.out.println(</span>"--------CSV文件已經寫入--------"<span style="color: #000000">); } </span><span style="color: #0000ff">catch</span><span style="color: #000000"> (IOException e) { e.printStackTrace(); } }</span></pre>

