我积累的Java实用代码

1、解压zip文件

/**
 * 解压输入的zip流,Java默认的解压只能处理UTF-8编码的文件或者目录名,否则会报MALFORMED异常
 * 
 * @param is 输入流
 * @param outputFolder 目标文件夹
 * @param charset zip文件中文件和目录名称使用的编码
 * @throws IOException 解压出错时抛出
 */
private void unzip(InputStream is, String outputFolder, Charset charset) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is), charset);
    ZipEntry ze = null;
    while ((ze = zis.getNextEntry()) != null) {
        String fileName = ze.getName();
        File newFile = new File(outputFolder + File.separator + fileName);
        if (ze.isDirectory()) {
            newFile.mkdirs();
        } else {
            newFile.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                bos.write(buffer, 0, len);
            }
            bos.close();
        }
    }
    zis.closeEntry();
    zis.close();
}

 

posted on 2017-06-13 14:59  buzzerrookie  阅读(236)  评论(0编辑  收藏  举报

导航