찾다
JavaJava베이스Java 파일 압축 잘못된 코드에 대한 솔루션

Java 파일 압축 잘못된 코드에 대한 솔루션

Dec 05, 2019 am 09:45 AM
java왜곡된 문자

Java 파일 압축 잘못된 코드에 대한 솔루션

1. 파일 압축 시 중국어 문자 깨짐 문제

1. 중국어 파일 이름 깨짐 문제 해결

압축 파일의 경우 파일 이름이 중국어인 경우 JDK API(java .util.zip.ZipEntry; java.util.zip.ZipOutputStream;) 압축이 완료된 후 압축된 패키지의 파일 이름이 깨져 있는 것을 볼 수 있습니다(파일의 내용이 깨져 있지 않음).

현재이 문제는 ANT의 ant.jar에 있는 클래스(org.apache.tools.zip.ZipEntry; org.apache.tools.zip.ZipOutputStream;)를 사용하여 해결할 수 있습니다.

추천: java 비디오 튜토리얼

2.ant.jar 종속성

<!-- ant.jar 用于解决文件解压缩乱码问题 -->
<dependency>
    <groupId>ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.6.5</version>
</dependency>

2. ZIP 압축 소스 코드의 JAVA 구현

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * zip压缩工具包
 * @Class ZipUtils
 */
public class ZipUtils {

    private final static Logger logger = LoggerFactory.getLogger(ZipUtils.class);

    private static final int BUFFER_SIZE = 2 * 1024;

    /**
     * 压缩成ZIP
     * @param srcFilePath 压缩文件路径
     * @param tarFilePath 目标ZIP输出路径
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *            false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception 压缩失败会抛出异常
     */
    public static boolean toZip(String srcFilePath, String tarFilePath, boolean KeepDirStructure) throws Exception {
        boolean isCompressSuccess = false;
        long start = System.currentTimeMillis();
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            File sourceFile = new File(srcFilePath);
            if (!sourceFile.exists()) {
                throw new FileNotFoundException("待压缩文件 [" + srcFilePath + "]不存在.");
            }
            fos = new FileOutputStream(new File(tarFilePath));
            zos = new ZipOutputStream(fos);
            // 设置压缩的编码,解决压缩路径中的中文乱码问题
            zos.setEncoding("UTF-8");            
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            isCompressSuccess = true;
            long end = System.currentTimeMillis();
            logger.info("【文件压缩】 压缩完成,耗时:{} ms", (end - start));
        } catch (Exception e) {
            logger.error("【文件压缩】 压缩失败", e);
            throw new RuntimeException("文件压缩失败", e);
        } finally {
            closeOutPutStream(zos);
            closeOutPutStream(fos);
        }
        return isCompressSuccess;
    }

    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zos zip输出流
     * @param name 压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *            false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
            throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }

    /**
     * 释放资源
     * @Title closeOutPutStream
     * @param ops
     * @return void
     */
    public static void closeOutPutStream(OutputStream ops) {
        if (ops != null) {
            try {
                ops.close();
            } catch(IOException ex) {
                logger.error("关闭输出流失败", ex);
            }
        }
    }

}

자바에 대한 자세한 내용은 java 기본 튜토리얼 컬럼을 참조하세요.

위 내용은 Java 파일 압축 잘못된 코드에 대한 솔루션의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경