用Java對CSV文件進行讀寫操作


需要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&lt;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>
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM