JAVA讀寫CSV文件


 最近工作需要,需要讀寫CSV文件的數據,簡單封裝了一下

 

依賴
讀寫CSV文件只需引用`javacsv`這個依賴就可以了

<dependency>
    <groupId>net.sourceforge.javacsv</groupId>
    <artifactId>javacsv</artifactId>
    <version>2.0</version>
</dependency>

 

讀文件

  /**
     * Read from CSV
     *
     * @param separator 分隔符
     * @param filePath 文件路徑
     * @return
     * */
    public static<T> List<T> readFromCSV(Character separator, String filePath) {
        CsvReader reader = null;
        List<T> result = new ArrayList<>();
        try {
            //如果生產文件亂碼,windows下用gbk,linux用UTF-8
            reader = new CsvReader(filePath, separator, Charset.forName("GBK"));

            // 讀取標題
            reader.readHeaders();
            // 逐條讀取記錄,直至讀完
            while (reader.readRecord()) {
                //讀取第一例
                reader.get(0);
                //讀取指定名字的列
                reader.get("");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                reader.close();
            }
        }

        return result;
    }

 

因為甜大王比較喜歡將讀取的一列封裝為一個Object,同時為了工具更通用返回的結果類型是一個List<T>

寫文件

/**
     * Write into CSV
     *
     * @param separator 分隔符
     * @param filePath 文件路徑
     * @param strList 對應CSV中的一行記錄
     * */
    public static void writeIntoCSV(Character separator, String filePath, List<List<String>> strList) {
        CsvWriter csvWriter = null;
        try {
            // 創建CSV寫對象
            csvWriter = new CsvWriter(filePath, separator, Charset.forName("GBK"));
            // 寫標題
            //String[] headers = {"FileName","FileSize","FileMD5"};
            //csvWriter.writeRecord(headers);
            for (List<String> list : strList) {
                    String[] writeLine = new String[list.size()];
                    list.toArray(writeLine);
                    csvWriter.writeRecord(writeLine);
            }

            csvWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != csvWriter) {
                csvWriter.close();
            }
        }
    }

 



附:完整代碼


免責聲明!

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



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