java导出csv,读写落盘,csv乱码,csv时间格式异常

第一步创建一个csv文件,添加UTF-8编码,防止乱码。

/**

* @param title 获取头部信息 * @param headers 获取首行信息,String[]数组类型 * @param fileName 获取文件名 * @return */ public File importCSV(String title, String[] headers, String fileName) { File file = null; try { //创立临时csv File tempFile = createBomCsv(fileName); //创建写入CSV对象,对象为创立的临时文件 CsvWriter csvWriter = new CsvWriter(new OutputStreamWriter(new FileOutputStream(tempFile.getCanonicalPath(), true), Charset.forName("UTF-8")), ','); //写入titile if (!"".equals(title)) { csvWriter.writeRecord(new String[]{title}); } //写入headers if (headers.length > 0) { csvWriter.writeRecord(headers); } csvWriter.flush(); csvWriter.close(); file = tempFile; } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); } return file; }
public File createBomCsv(String fileName) throws IOException {
        BufferedWriter bw = null;
        OutputStreamWriter osw = null;
        File out = null;
        try {
            out = FileUtil.createTempFile(fileName + "-" + FileUtils.getFileSuffixNumber() + FILE_SEPARATOR, ".csv", true);
            FileOutputStream fos = new FileOutputStream(out);
            fos.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            osw = new OutputStreamWriter(fos, "UTF-8");
            bw = new BufferedWriter(osw);
            bw.close();
            return out;
        } catch (IOException e) {
            logger.error(e.toString());
        } finally {
            if (bw != null) {
                bw.close();
            }
            if (osw == null) {
                osw.close();
            }
        }
        return out;
    }


第二步落盘文件信息:

/**
     * @param title    获取头部信息
     * @param headers  获取首行信息,String[]数组类型
     * @param fileName 获取文件名
     * @return
     */
    public File importCSV(String title, String[] headers, String fileName) {
        File file = null;
        try {
            //创立临时csv
            File tempFile = createBomCsv(fileName);
            //创建写入CSV对象,对象为创立的临时文件
            CsvWriter csvWriter = new CsvWriter(new OutputStreamWriter(new FileOutputStream(tempFile.getCanonicalPath(), true), Charset.forName("UTF-8")), ',');
            //写入titile
            if (!"".equals(title)) {
                csvWriter.writeRecord(new String[]{title});
            }
            //写入headers
            if (headers.length > 0) {
                csvWriter.writeRecord(headers);
            }
            csvWriter.flush();
            csvWriter.close();
            file = tempFile;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return file;
    }

猜你喜欢

转载自blog.csdn.net/xionglangs/article/details/80914945
csv