java 压缩文件

一,介绍

  今天来介绍下java读写文件和压缩功能

二,读

  1,读取文件

  实际开发中,从磁盘上读取文件一般很少,大多从第三方接口,如http请求获取、网关获取。

  获取的结果都是差不多,都是流对象,为了测试方便,代码就从本地获取。

  2,代码

/**
     * 按行读取文件
     * @param path
     */
    public static void readFile(String path){
        try {
            File file = new File(path);
            BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
            String strLine = null;
            int lineCount = 1;
            while(null != (strLine = bufferedReader.readLine())){
                logger.info("第[" + lineCount + "]行数据:[" + strLine + "]");
                lineCount++;
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

代码采用的是FileReader,也可以用FileInputStream获取字节

/**
     * 一次性读取全部文件数据
     * @param path
     */
    public static void readFile(String path){
        try{
            InputStream is = new FileInputStream(path);
            int len= is.available();
            byte[] bytes = new byte[len];
            is.read(bytes);
            logger.info("文件内容:\n" + new String(bytes));
            is.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

三,写

  

/**
    *  将文件数据写到磁盘
    * @param outputStream
    * @param path
    */
    public static void outFile(OutputStream outputStream, String path){
        try{
            FileOutputSteam fileOutStream = new FileOutputStream(path);
            fileOutputStream.write(outputStream.toByteArray());
        }catch(Exception e){
            e.printStackTrace();
        } 
}

其中outputStream是从inputStream写过来的,比如outputStream.write(inputStream.toByteArray())。

四,压缩

  开发中,元数据如果过大,可以考虑压缩数据,java中也提供相关的类,ZipOutputStream

  代码:

/**
    * 压缩文件
    * @param
    * @param
    */
public static void zipOutFile(String path){
    ByteArrayOutputStream outputStream1
= new ByteArrayOutputStream();     ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream1, Charset.forName("GBK"));
    f
or (int i = 1; i <= 500; i++) {
      ByteArrayOutputStream outputStream
= new ByteArrayOutputStream();       outputStream.write(inputStream.toByteArray());       zipOutputStream.putNextEntry(new ZipEntry("tmp" + name_index + ".csv")); zipOutputStream.write(outputStream.toByteArray());       zipOutputStream.closeEntry();       name_index++;
    }
    try{
            FileOutputSteam fileOutStream = new FileOutputStream(path);
            fileOutputStream.write(outputStream1.toByteArray);
        }catch(Exception e){
            e.printStackTrace();
        }
}

1,代码中outputStream1存放的是zipOutputStream压缩的内容,其中是压缩包,压缩着1、2、3.csv

2,先将读取到的inputStream放到outPutStream,然后压缩outputStream到outputStream1,最后将outputStream1写到磁盘上。

3,实际生产上,一般不会写到本地,直接上传服务器,如持久化网关服务等,为了测试大家看着就行。

posted @ 2021-01-06 10:34  superChong  阅读(504)  评论(0编辑  收藏  举报