Java对zip,rar,7z文件带密码解压实例详解

目录
  • 前言
  • 实现代码
    • 1、pom.xml
    • 2、zip解压
    • 3、rar解压
    • 4、7z解压
    • 5、解压统一入口封装
    • 6、测试代码
  • 补充

前言

在一些日常业务中,会遇到一些琐碎文件需要统一打包到一个压缩包中上传,业务方在后台接收到压缩包后自行解压,然后解析相应文件。而且可能涉及安全保密,因此会在压缩时带上密码,要求后台业务可以指定密码进行解压。

应用环境说明:jdk1.8,maven3.x,需要基于java语言实现对zip、rar、7z等常见压缩包的解压工作。

首先关于zip和rar、7z等压缩工具和压缩算法就不在此赘述,下面通过一个数据对比,使用上述三种不同的压缩算法,采用默认的压缩方式,看到压缩的文件大小如下:

转换成图表看得更直观,如下图:

从以上图表可以看到,7z的压缩率是最高,而zip压缩率比较低,rar比zip稍微好点。单纯从压缩率看,7z>rar4>rar5>zip。

实现代码

下面具体说明在java中如何进行相应解压:

1、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yelang</groupId>
    <artifactId>7zdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>2.9.0</version>
        </dependency>

        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding</artifactId>
            <version>16.02-2.01</version>
        </dependency>
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding-all-platforms</artifactId>
            <version>16.02-2.01</version>
        </dependency>

        <dependency>
            <groupId>org.tukaani</groupId>
            <artifactId>xz</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.21</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/fr.opensagres.xdocreport/xdocreport -->
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>xdocreport</artifactId>
            <version>1.0.6</version>
        </dependency>

    </dependencies>
</project>

主要依赖的jar包有:zip4j、sevenzipjbinding等。

2、zip解压

 @SuppressWarnings("resource")
private static String unZip(String rootPath, String sourceRarPath, String destDirPath, String passWord) {
        ZipFile zipFile = null;
        String result = "";
        try {
            //String filePath = sourceRarPath;
            String filePath = rootPath + sourceRarPath;
            if (StringUtils.isNotBlank(passWord)) {
                zipFile = new ZipFile(filePath, passWord.toCharArray());
            } else {
                zipFile = new ZipFile(filePath);
            }
            zipFile.setCharset(Charset.forName("GBK"));
            zipFile.extractAll(rootPath + destDirPath);
        } catch (Exception e) {
            log.error("unZip error", e);
            return e.getMessage();
        }
        return result;
    }

3、rar解压

private static String unRar(String rootPath, String sourceRarPath, String destDirPath, String passWord) {
        String rarDir = rootPath + sourceRarPath;
        String outDir = rootPath + destDirPath + File.separator;
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;
        try {
            // 第一个参数是需要解压的压缩包路径,第二个参数参考JdkAPI文档的RandomAccessFile
            randomAccessFile = new RandomAccessFile(rarDir, "r");
            if (StringUtils.isNotBlank(passWord))
                inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile), passWord);
            else
                inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));

            ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
            for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                final int[] hash = new int[]{0};
                if (!item.isFolder()) {
                    ExtractOperationResult result;
                    final long[] sizeArray = new long[1];

                    File outFile = new File(outDir + item.getPath());
                    File parent = outFile.getParentFile();
                    if ((!parent.exists()) && (!parent.mkdirs())) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(passWord)) {
                        result = item.extractSlow(data -> {
                            try {
                                IOUtils.write(data, new FileOutputStream(outFile, true));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            hash[0] ^= Arrays.hashCode(data); // Consume data
                            sizeArray[0] += data.length;
                            return data.length; // Return amount of consumed
                        }, passWord);
                    } else {
                        result = item.extractSlow(data -> {
                            try {
                                IOUtils.write(data, new FileOutputStream(outFile, true));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            hash[0] ^= Arrays.hashCode(data); // Consume data
                            sizeArray[0] += data.length;
                            return data.length; // Return amount of consumed
                        });
                    }

                    if (result == ExtractOperationResult.OK) {
                        log.error("解压rar成功...." + String.format("%9X | %10s | %s", hash[0], sizeArray[0], item.getPath()));
                    } else if (StringUtils.isNotBlank(passWord)) {
                        log.error("解压rar成功:密码错误或者其他错误...." + result);
                        return "password";
                    } else {
                        return "rar error";
                    }
                }
            }

        } catch (Exception e) {
            log.error("unRar error", e);
            return e.getMessage();
        } finally {
            try {
                inArchive.close();
                randomAccessFile.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

4、7z解压

 private static String un7z(String rootPath, String sourceRarPath, String destDirPath, String passWord) {
        try {
            File srcFile = new File(rootPath + sourceRarPath);//获取当前压缩文件
            // 判断源文件是否存在
            if (!srcFile.exists()) {
                throw new Exception(srcFile.getPath() + "所指文件不存在");
            }
            //开始解压
            SevenZFile zIn = null;
            if (StringUtils.isNotBlank(passWord)) {
                zIn = new SevenZFile(srcFile, passWord.toCharArray());
            }  else {
                zIn = new SevenZFile(srcFile);
            }

            SevenZArchiveEntry entry = null;
            File file = null;
            while ((entry = zIn.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    file = new File(rootPath + destDirPath, entry.getName());
                    if (!file.exists()) {
                        new File(file.getParent()).mkdirs();//创建此文件的上级目录
                    }
                    OutputStream out = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(out);
                    int len = -1;
                    byte[] buf = new byte[1024];
                    while ((len = zIn.read(buf)) != -1) {
                        bos.write(buf, 0, len);
                    }
                    // 关流顺序,先打开的后关闭
                    bos.close();
                    out.close();
                }
            }

        } catch (Exception e) {
            log.error("un7z is error", e);
            return e.getMessage();
        }
        return "";
    }

5、解压统一入口封装

public static Map<String,Object> unFile(String rootPath, String sourcePath, String destDirPath, String passWord) {
        Map<String,Object> resultMap = new HashMap<String, Object>();
        String result = "";
        if (sourcePath.toLowerCase().endsWith(".zip")) {
            //Wrong password!
            result = unZip(rootPath, sourcePath, destDirPath, passWord);
        } else if (sourcePath.toLowerCase().endsWith(".rar")) {
            //java.security.InvalidAlgorithmParameterException: password should be specified
            result = unRar(rootPath, sourcePath, destDirPath, passWord);
            System.out.println(result);
        } else if (sourcePath.toLowerCase().endsWith(".7z")) {
            //PasswordRequiredException: Cannot read encrypted content from G:\ziptest\11111111.7z without a password
            result = un7z(rootPath, sourcePath, destDirPath, passWord);
        }

        resultMap.put("resultMsg", 1);
        if (StringUtils.isNotBlank(result)) {
            if (result.contains("password")) resultMap.put("resultMsg", 2);
            if (!result.contains("password")) resultMap.put("resultMsg", 3);
        }
        resultMap.put("files", null);
        //System.out.println(result + "==============");
        return resultMap;
    }

6、测试代码

Long start = System.currentTimeMillis();
unFile("D:/rarfetch0628/","apache-tomcat-8.5.69.zip","apache-tomcat-zip","222");
long end = System.currentTimeMillis();
System.out.println("zip解压耗时==" + (end - start) + "毫秒");
System.out.println("============================================================");

Long rar4start = System.currentTimeMillis();
unFile("D:/rarfetch0628/","apache-tomcat-8.5.69-4.rar","apache-tomcat-rar4","222");
long rar4end = System.currentTimeMillis();
System.out.println("rar4解压耗时==" + (rar4end - rar4start)+ "毫秒");
System.out.println("============================================================");

Long rar5start = System.currentTimeMillis();
unFile("D:/rarfetch0628/","apache-tomcat-8.5.69-5.rar","apache-tomcat-rar5","222");
long rar5end = System.currentTimeMillis();
System.out.println("rar5解压耗时==" + (rar5end - rar5start)+ "毫秒");
System.out.println("============================================================");

Long zstart = System.currentTimeMillis();
unFile("D:/rarfetch0628/","apache-tomcat-8.5.69.7z","apache-tomcat-7z","222");
long zend = System.currentTimeMillis();
System.out.println("7z解压耗时==" + (zend - zstart)+ "毫秒");
System.out.println("============================================================");

在控制台中可以看到以下结果:

总结:本文采用java语言实现了对zip和rar、7z文件的解压统一算法。并对比了相应的解压速度,支持传入密码进行在线解压。

本文参考代码在补充内容里,不过代码直接运行有问题,这里进行了调整,主要优化的点如下:

1、pom.xml 遗漏了slf4j、commons-lang3、xdocreport等依赖

2、zip路径优化

3、去掉一些无用信息

4、优化异常信息

补充

1.maven引用

<dependency>
   <groupId>net.lingala.zip4j</groupId>
   <artifactId>zip4j</artifactId>
   <version>2.9.0</version>
</dependency>

<dependency>
   <groupId>net.sf.sevenzipjbinding</groupId>
   <artifactId>sevenzipjbinding</artifactId>
   <version>16.02-2.01</version>
</dependency>
<dependency>
   <groupId>net.sf.sevenzipjbinding</groupId>
   <artifactId>sevenzipjbinding-all-platforms</artifactId>
   <version>16.02-2.01</version>
</dependency>

<dependency>
   <groupId>org.tukaani</groupId>
   <artifactId>xz</artifactId>
   <version>1.9</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.21</version>
</dependency>

2.实现代码如下

import fr.opensagres.xdocreport.core.io.IOUtils;
import net.lingala.zip4j.ZipFile;
import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;

public class ZipAndRarTools {
    private static final Logger log = LoggerFactory.getLogger(ZipAndRarTools.class);

    /*
    解压zip
    */
    private static String unZip(String rootPath, String sourceRarPath, String destDirPath, String passWord) {
        ZipFile zipFile = null;

        try {

            if (StringUtils.isNotBlank(passWord)) {
                zipFile = new ZipFile(filePath, passWord.toCharArray());
            } else {
                zipFile = new ZipFile(filePath);
            }
            zipFile.extractAll(rootPath + destDirPath);
        } catch (Exception e) {
            log.error("unZip error", e);
            return e.getMessage();
        }
        return "";
    }

    /*
       解压rar rar5
       */
    private static String unRar(String rootPath, String sourceRarPath, String destDirPath, String passWord) {
         /*final File rar = new File(rootPath + sourceRarPath);
       final File destinationFolder = new File(rootPath + destDirPath);
        destinationFolder.mkdir();
        try {
            Junrar.extract(rar, destinationFolder);
        } catch (Exception e) {
            log.error("unRar error", e);
            return e.getMessage();
        }*/

        String rarDir = rootPath + sourceRarPath;
        String outDir = rootPath + destDirPath + File.separator;
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;
        try {
            // 第一个参数是需要解压的压缩包路径,第二个参数参考JdkAPI文档的RandomAccessFile
            randomAccessFile = new RandomAccessFile(rarDir, "r");
            if (StringUtils.isNotBlank(passWord))
                inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile), passWord);
            else
                inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));

            ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
            for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                final int[] hash = new int[]{0};
                if (!item.isFolder()) {
                    ExtractOperationResult result;
                    final long[] sizeArray = new long[1];

                    File outFile = new File(outDir + item.getPath());
                    File parent = outFile.getParentFile();
                    if ((!parent.exists()) && (!parent.mkdirs())) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(passWord)) {
                        result = item.extractSlow(data -> {
                            try {
                                IOUtils.write(data, new FileOutputStream(outFile, true));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            hash[0] ^= Arrays.hashCode(data); // Consume data
                            sizeArray[0] += data.length;
                            return data.length; // Return amount of consumed
                        }, passWord);
                    } else {
                        result = item.extractSlow(data -> {
                            try {
                                IOUtils.write(data, new FileOutputStream(outFile, true));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            hash[0] ^= Arrays.hashCode(data); // Consume data
                            sizeArray[0] += data.length;
                            return data.length; // Return amount of consumed
                        });
                    }

                    if (result == ExtractOperationResult.OK) {
                        log.error("解压rar成功...." + String.format("%9X | %10s | %s", hash[0], sizeArray[0], item.getPath()));
                    } else if (StringUtils.isNotBlank(passWord)) {
                        log.error("解压rar成功:密码错误或者其他错误...." + result);
                        return "password";
                    } else {
                        return "rar error";
                    }
                }
            }

        } catch (Exception e) {
            log.error("unRar error", e);
            return e.getMessage();
        } finally {
            try {
                inArchive.close();
                randomAccessFile.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /*
     * 解压7z
     */
    private static String un7z(String rootPath, String sourceRarPath, String destDirPath, String passWord) {
        try {
            File srcFile = new File(rootPath + sourceRarPath);//获取当前压缩文件
            // 判断源文件是否存在
            if (!srcFile.exists()) {
                throw new Exception(srcFile.getPath() + "所指文件不存在");
            }
            //开始解压
            SevenZFile zIn = null;
            if (StringUtils.isNotBlank(passWord))
                new SevenZFile(srcFile, passWord.getBytes());
            else
                new SevenZFile(srcFile);

            SevenZArchiveEntry entry = null;
            File file = null;
            while ((entry = zIn.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    file = new File(rootPath + destDirPath, entry.getName());
                    if (!file.exists()) {
                        new File(file.getParent()).mkdirs();//创建此文件的上级目录
                    }
                    OutputStream out = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(out);
                    int len = -1;
                    byte[] buf = new byte[1024];
                    while ((len = zIn.read(buf)) != -1) {
                        bos.write(buf, 0, len);
                    }
                    // 关流顺序,先打开的后关闭
                    bos.close();
                    out.close();
                }
            }

        } catch (Exception e) {
            log.error("un7z is error", e);
            return e.getMessage();
        }
        return "";
    }

    public static void unFile(String rootPath, String sourcePath, String destDirPath, String passWord) {
        String result = "";
        if (sourcePath.toLowerCase().endsWith(".zip")) {
            //Wrong password!
            result = unZip(rootPath, sourcePath, destDirPath, passWord);
        } else if (sourcePath.toLowerCase().endsWith(".rar")) {
            //java.security.InvalidAlgorithmParameterException: password should be specified
            result = unRar(rootPath, sourcePath, destDirPath, passWord);
        } else if (sourcePath.toLowerCase().endsWith(".7z")) {
            //PasswordRequiredException: Cannot read encrypted content from G:\ziptest\11111111.7z without a password
            result = un7z(rootPath, sourcePath, destDirPath, passWord);
        }

        resultMap.put("resultMsg", 1);
        if (StringUtils.isNotBlank(result)) {
            if (result.contains("password")) resultMap.put("resultMsg", 2);
            if (!result.contains("password")) resultMap.put("resultMsg", 3);
        }
        resultMap.put("files", data);
//        System.out.println(result + "==============");
        return resultMap;
    }

    public static void main(String[] args) {
        getFileList("G:\\ziptest\\", "测试.zip", "test3333", "密码");
    }

}

以上就是Java对zip,rar,7z文件带密码解压实例详解的详细内容,更多关于Java文件带密码解压的资料请关注我们其它相关文章!

(0)

相关推荐

  • Java解压和压缩带密码的zip文件过程详解

    前言 JDK自带的ZIP操作接口(java.util.zip包,请参看文章末尾的博客链接)并不支持密码,甚至也不支持中文文件名. 为了解决ZIP压缩文件的密码问题,在网上搜索良久,终于找到了winzipaes开源项目. 该项目在google code下托管 ,仅支持AES压缩和解压zip文件( This library only supports Win-Zip's 256-Bit AES mode.).网站上下载的文件是源代码,最新版本为winzipaes_src_20120416.zip,本

  • Java实现文件压缩为zip和解压zip压缩包

    目录 压缩成.zip 解压.zip 压缩成.zip 代码如下: /** * 压缩成ZIP * * @param srcDir 压缩文件夹路径 * @param out 压缩文件输出流 * @throws RuntimeException 压缩失败会抛出运行时异常 */ public static void toZip(String srcDir, OutputStream out) throws RuntimeException { long start = System.currentTime

  • java 压缩和解压缩Zip、Jar、Gzip文件实例代码

    我们经常会使用WinZIP等压缩软件将文件进行压缩以方便传输.在java里面也提供了将文件进行压缩以减少传输时的数据量的类,可以很方便的将文件压缩成ZIP.JAR.GZIP等形式,GZIP主要是在Linux系统下的压缩文件. 下面主要讲的就是ZIP形式的压缩文件,而JAR.GZIP形式的压缩文件也是类似的用法. ZIP是一种很常见的压缩形式,在java中要实现ZIP的压缩主要用到的是java.util.zip这个包里面的类.主要有ZipFile. ZipOutputStream.ZipInput

  • Java 文件解压缩实现代码

    Java实现压缩文件的解压缩操作,缺点是压缩文件内不能含有文件名为中文的的文件,否则会出现如下错误: 复制代码 代码如下: Exception in thread "main" java.lang.IllegalArgumentException: MALFORMED at java.util.zip.ZipCoder.toString(Unknown Source) at java.util.zip.ZipInputStream.readLOC(Unknown Source) at

  • java使用gzip实现文件解压缩示例

    复制代码 代码如下: package com.cjonline.foundation.cpe.action; import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.

  • java解压zip文件示例

    若是使用Java自带的压缩工具包来实现解压缩文件到指定文件夹的功能,因为jdk提供的zip只能按UTF-8格式处理,而Windows系统中文件名是以GBK方式编码的,所以如果是解压一个包含中文文件名的zip包,会报非法参数异常,所以要实现解压缩,就得对DeflaterOutputStream.java.InflaterInputStream.java.ZipConstants.java.ZipEntry.java.ZipInputStream.java以及ZipOutputStream.java

  • Java对zip,rar,7z文件带密码解压实例详解

    目录 前言 实现代码 1.pom.xml 2.zip解压 3.rar解压 4.7z解压 5.解压统一入口封装 6.测试代码 补充 前言 在一些日常业务中,会遇到一些琐碎文件需要统一打包到一个压缩包中上传,业务方在后台接收到压缩包后自行解压,然后解析相应文件.而且可能涉及安全保密,因此会在压缩时带上密码,要求后台业务可以指定密码进行解压. 应用环境说明:jdk1.8,maven3.x,需要基于java语言实现对zip.rar.7z等常见压缩包的解压工作. 首先关于zip和rar.7z等压缩工具和压

  • FasfDFS整合Java实现文件上传下载功能实例详解

    在上篇文章给大家介绍了FastDFS安装和配置整合Nginx-1.13.3的方法,大家可以点击查看下. 今天使用Java代码实现文件的上传和下载.对此作者提供了Java API支持,下载fastdfs-client-java将源码添加到项目中.或者在Maven项目pom.xml文件中添加依赖 <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</arti

  • 对python读取zip压缩文件里面的csv数据实例详解

    利用zipfile模块和pandas获取数据,代码比较简单,做个记录吧: # -*- coding: utf-8 -*- """ Created on Tue Aug 21 22:35:59 2018 @author: FanXiaoLei """ from zipfile import ZipFile import pandas as pd myzip=ZipFile('2.zip') f=myzip.open('2.csv') df=pd.r

  • Java实现读取项目中文件(.json或.properties)的方法详解

    目录 1. 读取json file 1.1 Json dependency 1.2 字节流 1.3 buffer reader 2. 读取properties file 3. 好看的css样式 1. 读取json file 1.1 Json dependency <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>

  • Linux下.tar.xz文件的解压教程详解

    前言 对于xz这个压缩相信很多人陌生,但xz是绝大数linux默认就带的一个压缩工具,xz格式比7z还要小. 最近在下载某个源码包的时候遇到的这种压缩格式,乘此机会分享一下xz的压缩与解压方法. 安装 如果系统没有xz命令,需要进行安装,安装方法非常简单, 在centos下,直接运行: yum install xz 也可以使用源码包安装: 先下载该工具源码包http://tukaani.org/xz/ 下载后解压进入该目录运行configure生成makefile文件用-prefix指定安装目录

  • Java 中的vector和list的区别和使用实例详解

    要了解vector,list,deque.我们先来了解一下STL. STL是Standard Template Library的简称,中文名是标准模板库.从根本上说,STL是一些容器和算法的集合.STL可分为容器(containers).迭代器(iterators).空间配置器(allocator).配接器(adapters).算法(algorithms).仿函数(functors)六个部分.指针被封装成迭代器,这里vector,list就是所谓的容器. 我们常常在实现链表,栈,队列或者数组时,

  • JavaWeb实现文件上传与下载实例详解

    在Web应用程序开发中,文件上传与下载功能是非常常用的功能,下面通过本文给大家介绍JavaWeb实现文件上传与下载实例详解. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具common-fileupload这个文件上传组件.这个common-fileupload上传组件的jar包可以去apache官网上面下载,common-fileupload是依赖于c

  • Spring加载properties文件的两种方式实例详解

    在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取properties里面的配置,这样后期只需要改动properties文件即可,不需要修改源代码,这样更加方便.在Spring中也可以这么做,而且Spring有两种加载properties文件的方式:基于xml方式和基于注解方式.下面分别讨论下这两种方式. 1. 通过xml方式加载properties文件 我们以Spring实例化dataSource为例,我们一般会在beans

  • Java并发编程:CountDownLatch与CyclicBarrier和Semaphore的实例详解

    Java并发编程:CountDownLatch与CyclicBarrier和Semaphore的实例详解 在java 1.5中,提供了一些非常有用的辅助类来帮助我们进行并发编程,比如CountDownLatch,CyclicBarrier和Semaphore,今天我们就来学习一下这三个辅助类的用法. 以下是本文目录大纲: 一.CountDownLatch用法 二.CyclicBarrier用法 三.Semaphore用法 若有不正之处请多多谅解,并欢迎批评指正. 一.CountDownLatch

  • java 中模拟UDP传输的发送端和接收端实例详解

    java 中模拟UDP传输的发送端和接收端实例详解 一.创建UDP传输的发送端 1.建立UDP的Socket服务: 2.将要发送的数据封装到数据包中: 3.通过UDP的Socket服务将数据包发送出去: 4.关闭Socket服务. import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class

随机推荐