java安全解压文件

方法一

public class Decompression {
    private static final Logger LOGGER = Logger.getLogger(Decompression.class);
 
    private static final int BUFFER = 512;
 
    private static final int TOO_BIG = 0x6400000;
 
    private static final int TOO_MANY = 1024;
 
    private Decompression() {
 
    }
 
    public static void zipUncompress(String inputFile, String destDirPath) {
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        ZipFile zipFile = null;
        try {
            File srcFile = new File(inputFile);
            if (!srcFile.exists()) {
                throw new IOException(srcFile.getPath());
            }
            zipFile = new ZipFile(srcFile);
            Enumeration entries = zipFile.entries();
            int total = 0;
            int entriesNumber = 0;
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                checkFileName(entry.getName(), destDirPath);
                int count = 0;
                if (entry.isDirectory()) {
                    if (!srcFile.mkdir()) {
                        throw new IOException();
                    }
                } else {
                    String fileName = Tools.delTimeStamp(entry.getName());
                    File targetFile = new File(destDirPath + File.separator + fileName);
                    if (!targetFile.getParentFile().exists()) {
                        if (targetFile.getParentFile().mkdirs()) {
                            throw new IOException();
                        }
                    }
                    if (!targetFile.createNewFile()) {
                        throw new IOException();
                    }
                    inputStream = zipFile.getInputStream(entry);
                    fileOutputStream = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[BUFFER];
                    while ((len = inputStream.read(buf)) != -1) {
                        total += count;
                        if (total > TOO_BIG) {
                            LOGGER.error("Zip file is too big.");
                            break;
                        }
                        fileOutputStream.write(buf, 0, len);
                    }
                    entriesNumber++;
                    if (total > TOO_BIG) {
                        LOGGER.error("Zip file is too big.");
                        break;
                    }
                    if (entriesNumber > TOO_MANY) {
                        LOGGER.error("Zip file is too many.");
                        break;
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.error("IOException error.", e);
        } finally {
            closeProcess(inputFile, fileOutputStream, inputStream, zipFile);
        }
    }
 
    private static String checkFileName(String entryName, String intendedDir) throws IOException {
        File file = new File(intendedDir, entryName);
        String canonicalPath1 = file.getCanonicalPath();
        File intendedFile = new File(intendedDir);
        String canonicalPath2 = intendedFile.getCanonicalPath();
        if (canonicalPath1.startsWith(canonicalPath2)) {
            return canonicalPath1;
        } else {
            throw new IllegalStateException();
        }
    }
 
    private static void closeProcess(String inputFile, FileOutputStream fileOutputStream, InputStream inputStream,
        ZipFile zipFile) {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (inputFile != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            LOGGER.error("Close error.", e);
        }
    }
}

方法二

public class Decompression {
    private static final Logger LOGGER = Logger.getLogger(Decompression.class);
 
    private static final int BUFFER = 512;
 
    private static final int TOO_BIG = 0x6400000;
 
    private static final int TOO_MANY = 1024;
 
    private Decompression() {
 
    }
 
    public static void zipUncompress(String inputFile, String destDirPath) {
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        ZipFile zipFile = null;
        try {
            File srcFile = new File(inputFile);
            if (!srcFile.exists()) {
                throw new IOException(srcFile.getPath());
            }
            zipFile = new ZipFile(srcFile);
            Enumeration entries = zipFile.entries();
            int total = 0;
            int entriesNumber = 0;
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                checkFileName(entry.getName(), destDirPath);
                int count = 0;
                if (entry.isDirectory()) {
                    if (!srcFile.mkdir()) {
                        throw new IOException();
                    }
                } else {
                    String fileName = Tools.delTimeStamp(entry.getName());
                    File targetFile = new File(destDirPath + File.separator + fileName);
                    if (!targetFile.getParentFile().exists()) {
                        if (targetFile.getParentFile().mkdirs()) {
                            throw new IOException();
                        }
                    }
                    if (!targetFile.createNewFile()) {
                        throw new IOException();
                    }
                    inputStream = zipFile.getInputStream(entry);
                    fileOutputStream = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[BUFFER];
                    while ((len = inputStream.read(buf)) != -1) {
                        total += count;
                        if (total > TOO_BIG) {
                            LOGGER.error("Zip file is too big.");
                            break;
                        }
                        fileOutputStream.write(buf, 0, len);
                    }
                    entriesNumber++;
                    if (total > TOO_BIG) {
                        LOGGER.error("Zip file is too big.");
                        break;
                    }
                    if (entriesNumber > TOO_MANY) {
                        LOGGER.error("Zip file is too many.");
                        break;
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.error("IOException error.", e);
        } finally {
            closeProcess(inputFile, fileOutputStream, inputStream, zipFile);
        }
    }
 
    private static String checkFileName(String entryName, String intendedDir) throws IOException {
        File file = new File(intendedDir, entryName);
        String canonicalPath1 = file.getCanonicalPath();
        File intendedFile = new File(intendedDir);
        String canonicalPath2 = intendedFile.getCanonicalPath();
        if (canonicalPath1.startsWith(canonicalPath2)) {
            return canonicalPath1;
        } else {
            throw new IllegalStateException();
        }
    }
 
    private static void closeProcess(String inputFile, FileOutputStream fileOutputStream, InputStream inputStream,
        ZipFile zipFile) {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (inputFile != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            LOGGER.error("Close error.", e);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Java有一些库可以用来创建RAR文件压缩文件,其中最常用的是 "junrar" 库。下面是使用 "junrar" 库来创建RAR压缩文件的基本步骤: 1. 在Java项目中添加 "junrar" 库的依赖项。你可以通过Maven或Gradle等构建工具将依赖项添加到项目中。 2. 创建一个 RarArchiveEntry 对象,用于描述要压缩的文件文件夹。 ```java RarArchiveEntry entry = new RarArchiveEntry(file, "filename.rar"); ``` 3. 创建一个 RarArchiveOutputStream 对象,用于写入压缩文件。 ```java RarArchiveOutputStream out = new RarArchiveOutputStream(new FileOutputStream(outputFile)); ``` 4. 使用 RarArchiveOutputStream 的 putArchiveEntry 方法将 RarArchiveEntry 对象写入输出流中。 ```java out.putArchiveEntry(entry); ``` 5. 将要压缩的文件写入输出流中。 ```java FileInputStream in = new FileInputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } ``` 6. 使用 RarArchiveOutputStream 的 closeArchiveEntry 方法关闭当前的 entry。 ```java out.closeArchiveEntry(); ``` 7. 最后,关闭 RarArchiveOutputStream 输出流。 ```java out.close(); ``` 完整的代码示例: ```java import org.apache.commons.compress.archivers.rar.RarArchiveEntry; import org.apache.commons.compress.archivers.rar.RarArchiveOutputStream; import java.io.*; public class CreateRarExample { public static void main(String[] args) throws IOException { File file = new File("path/to/file"); File outputFile = new File("path/to/output.rar"); RarArchiveEntry entry = new RarArchiveEntry(file, "filename.rar"); RarArchiveOutputStream out = new RarArchiveOutputStream(new FileOutputStream(outputFile)); out.putArchiveEntry(entry); FileInputStream in = new FileInputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.closeArchiveEntry(); out.close(); } } ``` 请注意,RAR格式受到版权保护,使用RAR格式需要遵循相关法律法规。 ### 回答2: 要创建RAR压缩文件Java库,可以按照以下步骤进行: 1. 导入RAR压缩库:首先,需要将RAR压缩库导入到Java开发环境中。可以从RAR官方网站或其他可信的资源网站下载RAR压缩库的jar文件。 2. 导入库并设置环境:将RAR压缩库的jar文件导入到Java项目的classpath中。可以在项目的构建路径或依赖管理中进行设置,确保可以在项目中使用RAR库的类和方法。 3. 引入库并初始化:在Java代码中,使用import语句引入RAR压缩库的相关类。然后,根据RAR压缩库的要求进行初始化工作,如设置压缩级别、密码等。 4. 创建RAR压缩文件:使用RAR压缩库提供的方法,创建一个新的RAR压缩文件。可以指定文件名、路径和压缩选项等信息。也可以选择性地设置密码,以提供额外的安全性。 5. 向RAR文件中添加文件:通过RAR压缩库的方法,将想要压缩的文件添加到创建的RAR压缩文件中。可以按照需要,添加一个或多个文件,并可以选择性地设定文件的压缩级别或密码。 6. 完成RAR文件的创建:在添加完所有要压缩的文件后,关闭RAR压缩文件,并将其保存到指定的目标路径中。确保文件保存成功,并在需要的时候可以正确地解压缩。 使用以上的步骤,可以创建一个用于压缩文件为RAR格式的Java库。这个库可以在Java项目中使用,方便地实现RAR文件的创建和管理,提供更多的文件压缩选项和安全性保护。 ### 回答3: 要创建RAR压缩文件Java库,您可以按照以下步骤进行操作。 首先,您需要了解RAR文件的格式和压缩算法。RAR是一种常见的压缩文件格式,它使用Roshal Archive压缩算法来压缩和存储文件。在Java中创建RAR文件需要使用RAR文件格式的规范以及相应的压缩算法。 第二步是编写Java代码来处理RAR文件。您可以使用Java的压缩库,如java.util.zip包中的类来处理ZIP文件。然而,对于RAR文件Java没有内置的库可以直接使用。因此,您需要查找第三方库或开源项目来处理RAR文件。 许多开源项目提供了RAR库的Java绑定,您可以选择适合您需求的库。例如,您可以使用JRar或SevenZip-JBinding等库来创建RAR压缩文件。 安装选定的库后,您可以按照库的文档和示例代码来创建RAR压缩文件。通常情况下,您需要创建一个RAR文件对象,然后添加要压缩的文件文件夹,并设置压缩选项(如压缩级别、密码等)。最后,您可以调用创建RAR文件的方法来生成RAR文件。 在创建RAR文件时,您还可以处理压缩过程中可能出现的错误或异常情况。例如,您可以捕获文件无法找到、无法读取或权限错误等异常,并相应地进行处理。 总结起来,为了创建RAR压缩文件Java库,您需要了解RAR文件格式和压缩算法,查找适合您需求的第三方库或开源项目,然后编写Java代码来操作RAR文件。这样,您可以通过调用库提供的方法和设置相应的参数来创建RAR压缩文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值