工具类--Java生成csv文件并压缩

csv文件支持excel文件格式打开,但是却不需要poi的支持,文件生成更加简单,方便,项目中需要用到csv文件,做下记录:

1.生成csv文件:

/**
     * <生成csv文件>
     *
     * @param fileName    fileName
     * @param filePath    filePath
     * @param colNameList colNameList
     * @param dataList    dataList
     * @return filePath+fileName
     * @throws
     */
    public static String generateCsv(String filePath, String fileName,
                                     List<String> colNameList, List<List<String>> dataList)
        throws IOException
    {
        BufferedWriter csvWrite = null;
        String fileRealPath = filePath + fileName + ".csv";

        try
        {
            //定义文件类型
            File csvFile = new File(fileRealPath);

            //获取文件目录
            File parent = csvFile.getParentFile();
            if (!parent.exists())
            {
                parent.mkdirs();
            }

            //创建文件
            csvFile.createNewFile();
            csvWrite = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024);

            //写入表头
            write(colNameList, csvWrite);
            //写入数据
            for (List<String> dataPerRow : dataList)
            {
                write(dataPerRow, csvWrite);
            }
            csvWrite.flush();

            return fileRealPath;
        }
        catch (IOException e)
        {
            LOGGER.error("csv文件生成失败,原因:", e);
            throw new IOException("csv文件生成失败");
        }
        finally
        {

            try
            {
                if (null != csvWrite)
                {
                    csvWrite.close();
                }
            }
            catch (IOException e)
            {
                LOGGER.error("关闭文件流失败,原因:", e);
                throw new IOException("关闭文件流失败");
            }
        }
    }

/**
     *      * 将数据按行写入数据
     *      *
     *      * @param dataList
     *      * @param csvWreite
     *      * @throws IOException
     *      
     */
    private static void write(List<String> dataList, BufferedWriter csvWrite)
        throws IOException
    {
        for (String data : dataList)
        {
            StringBuffer buffer = new StringBuffer();
            String rowStr = buffer.append("\"").append(data).append("\",").toString();
            csvWrite.write(rowStr);
        }
        csvWrite.newLine();
    }

上面的生成文件的编码格式需要改成GB2312,不然生成的csv文件用excel打开时,中文会出现乱码及行错乱的问题。

2.将生成的csv文件压缩成zip

/**
     * @param fileRealPathList 待压缩的文件列表
     * @param zipFileRealPath  压缩后的文件名称
     * @return boolean
     * @throws :Exception
     * @Function: zipFiles
     * @Description:多个文件的ZIP压缩
     */
    public static void zipFiles(List<String> fileRealPathList, String zipFileRealPath)
        throws IOException
    {
        FileOutputStream out = null;
        ZipOutputStream zipOut = null;
        try
        {
            // 根据文件路径构造一个文件实例
            File zipFile = new File(zipFileRealPath);
            // 判断目前文件是否存在,如果不存在,则新建一个
            if (!zipFile.exists())
            {
                zipFile.createNewFile();
            }
            // 根据文件路径构造一个文件输出流
            out = new FileOutputStream(zipFileRealPath);
            // 传入文件输出流对象,创建ZIP数据输出流对象
            zipOut = new ZipOutputStream(out);
            // 循环待压缩的文件列表
            for (String fileRealPath : fileRealPathList)
            {
                FileInputStream in = null;
                try
                {
                    File file = new File(fileRealPath);
                    if (!file.exists())
                    {
                        LOGGER.error("文件不存在");
                        throw new FileNotFoundException("文件不存在");
                    }

                    // 创建文件输入流对象
                    in = new FileInputStream(fileRealPath);
                    // 得到当前文件的文件名称
                    //判断操作系统
                    String separateCharacter = "";
                    String os = System.getProperty("os.name");
                    if (os.toLowerCase().startsWith("win"))
                    {
                        //windows操作系统
                        separateCharacter = "\\";
                    }
                    else
                    {
                        //非windows操作系统
                        separateCharacter = "/";
                    }
                    String fileName = fileRealPath.substring(
                        fileRealPath.lastIndexOf(separateCharacter) + 1, fileRealPath.length());
                    // 创建指向压缩原始文件的入口
                    ZipEntry entry = new ZipEntry(fileName);
                    zipOut.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber = 0;
                    byte[] buffer = new byte[512];
                    while ((nNumber = in.read(buffer)) != -1)
                    {
                        zipOut.write(buffer, 0, nNumber);
                    }
                }
                catch (IOException e)
                {
                    LOGGER.error("文件压缩异常-in,原因:", e);
                    throw new IOException("文件压缩异常");
                }
                finally
                {
                    // 关闭创建的流对象
                    if (null != in)
                    {
                        in.close();
                    }
                }
            }
        }
        catch (IOException e)
        {
            LOGGER.error("文件压缩异常-out,原因:", e);
            throw new IOException("文件压缩异常");
        }
        finally
        {
            if (null != zipOut)
            {
                zipOut.close();
            }
            if (null != out)
            {
                out.close();
            }
        }
    }

3.将之前生成的csv文件删除

/**
     * 批量删除文件
     *
     * @param fileRealPathList 文件绝对路径(带文件名)
     */
    public static void deleteFiles(List<String> fileRealPathList)
        throws IOException
    {
        if (!CollectionUtils.isEmpty(fileRealPathList))
        {
            File file = null;
            for (String fileRealPath : fileRealPathList)
            {
                file = new File(fileRealPath);
                if (file.exists() && file.isFile())
                {
                    file.delete();
                }
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/wangchaox123/article/details/93646324
今日推荐