使用Java对文件或文件夹的压缩, 解压, 加密和解密. 加解密类型使用的是AES.
使用zip对文件或文件夹进行压缩, 解压缩:
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipInputStream;
- import java.util.zip.ZipOutputStream;
- /**
- * 对文件或文件夹进行压缩和解压
- *
- */
- public class ZipUtil {
- /**得到当前系统的分隔符*/
- // private static String separator = System.getProperty("file.separator");
- /**
- * 添加到压缩文件中
- * @param out
- * @param f
- * @param base
- * @throws Exception
- */
- private void directoryZip(ZipOutputStream out, File f, String base) throws Exception {
- // 如果传入的是目录
- if (f.isDirectory()) {
- File[] fl = f.listFiles();
- // 创建压缩的子目录
- out.putNextEntry(new ZipEntry(base + "/"));
- if (base.length() == 0) {
- base = "";
- } else {
- base = base + "/";
- }
- for (int i = 0; i < fl.length; i++) {
- directoryZip(out, fl[i], base + fl[i].getName());
- }
- } else {
- // 把压缩文件加入rar中
- out.putNextEntry(new ZipEntry(base));
- FileInputStream in = new FileInputStream(f);
- byte[] bb = new byte[10240];
- int aa = 0;
- while ((aa = in.read(bb)) != -1) {
- out.write(bb, 0, aa);
- }
- in.close();
- }
- }
- /**
- * 压缩文件
- *
- * @param zos
- * @param file
- * @throws Exception
- */
- private void fileZip(ZipOutputStream zos, File file) throws Exception {
- if (file.isFile()) {
- zos.putNextEntry(new ZipEntry(file.getName()));
- FileInputStream fis = new FileInputStream(file);
- byte[] bb = new byte[10240];
- int aa = 0;
- while ((aa = fis.read(bb)) != -1) {
- zos.write(bb, 0, aa);
- }
- fis.close();
- System.out.println(file.getName());
- } else {
- directoryZip(zos, file, "");
- }
- }
- /**
- * 解压缩文件
- *
- * @param zis
- * @param file
- * @throws Exception
- */
- private void fileUnZip(ZipInputStream zis, File file) throws Exception {
- ZipEntry zip = zis.getNextEntry();
- if (zip == null)
- return;
- String name = zip.getName();
- File f = new File(file.getAbsolutePath() + "/" + name);
- if (zip.isDirectory()) {
- f.mkdirs();
- fileUnZip(zis, file);
- } else {
- f.createNewFile();
- FileOutputStream fos = new FileOutputStream(f);
- byte b[] = new byte[10240];
- int aa = 0;
- while ((aa = zis.read(b)) != -1) {
- fos.write(b, 0, aa);
- }
- fos.close();
- fileUnZip(zis, file);
- }
- }
- /**
- * 根据filePath创建相应的目录
- * @param filePath
- * @return
- * @throws IOException
- */
- private File mkdirFiles(String filePath) throws IOException{
- File file = new File(filePath);
- if(!file.getParentFile().exists()){
- file.getParentFile().mkdirs();
- }
- file.createNewFile();
- return file;
- }
- /**
- * 对zipBeforeFile目录下的文件压缩,保存为指定的文件zipAfterFile
- *
- * @param zipBeforeFile 压缩之前的文件
- * @param zipAfterFile 压缩之后的文件
- */
- public void zip(String zipBeforeFile, String zipAfterFile) {
- try {
- ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(mkdirFiles(zipAfterFile)));
- fileZip(zos, new File(zipBeforeFile));
- zos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 解压缩文件unZipBeforeFile保存在unZipAfterFile目录下
- *
- * @param unZipBeforeFile 解压之前的文件
- * @param unZipAfterFile 解压之后的文件
- */
- public void unZip(String unZipBeforeFile, String unZipAfterFile) {
- try {
- ZipInputStream zis = new ZipInputStream(new FileInputStream(unZipBeforeFile));
- File f = new File(unZipAfterFile);
- f.mkdirs();
- fileUnZip(zis, f);
- zis.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipInputStream;
- import java.util.zip.ZipOutputStream;
- /**
- * 对文件或文件夹进行压缩和解压
- *
- */
- public class ZipUtil {
- /**得到当前系统的分隔符*/
- // private static String separator = System.getProperty("file.separator");
- /**
- * 添加到压缩文件中
- * @param out
- * @param f
- * @param base
- * @throws Exception
- */
- private void directoryZip(ZipOutputStream out, File f, String base) throws Exception {
- // 如果传入的是目录
- if (f.isDirectory()) {
- File[] fl = f.listFiles();
- // 创建压缩的子目录
- out.putNextEntry(new ZipEntry(base + "/"));
- if (base.length() == 0) {
- base = "";
- } else {
- base = base + "/";
- }
- for (int i = 0; i < fl.length; i++) {
- directoryZip(out, fl[i], base + fl[i].getName());
- }
- } else {
- // 把压缩文件加入rar中
- out.putNextEntry(new ZipEntry(base));
- FileInputStream in = new FileInputStream(f);
- byte[] bb = new byte[10240];
- int aa = 0;
- while ((aa = in.read(bb)) != -1) {
- out.write(bb, 0, aa);
- }
- in.close();
- }
- }
- /**
- * 压缩文件
- *
- * @param zos
- * @param file
- * @throws Exception
- */
- private void fileZip(ZipOutputStream zos, File file) throws Exception {
- if (file.isFile()) {
- zos.putNextEntry(new ZipEntry(file.getName()));
- FileInputStream fis = new FileInputStream(file);
- byte[] bb = new byte[10240];
- int aa = 0;
- while ((aa = fis.read(bb)) != -1) {
- zos.write(bb, 0, aa);
- }
- fis.close();
- System.out.println(file.getName());
- } else {
- directoryZip(zos, file, "");
- }
- }
- /**
- * 解压缩文件
- *
- * @param zis
- * @param file
- * @throws Exception
- */
- private void fileUnZip(ZipInputStream zis, File file) throws Exception {
- ZipEntry zip = zis.getNextEntry();
- if (zip == null)
- return;
- String name = zip.getName();
- File f = new File(file.getAbsolutePath() + "/" + name);
- if (zip.isDirectory()) {
- f.mkdirs();
- fileUnZip(zis, file);
- } else {
- f.createNewFile();
- FileOutputStream fos = new FileOutputStream(f);
- byte b[] = new byte[10240];
- int aa = 0;
- while ((aa = zis.read(b)) != -1) {
- fos.write(b, 0, aa);
- }
- fos.close();
- fileUnZip(zis, file);
- }
- }
- /**
- * 根据filePath创建相应的目录
- * @param filePath
- * @return
- * @throws IOException
- */
- private File mkdirFiles(String filePath) throws IOException{
- File file = new File(filePath);
- if(!file.getParentFile().exists()){
- file.getParentFile().mkdirs();
- }
- file.createNewFile();
- return file;
- }
- /**
- * 对zipBeforeFile目录下的文件压缩,保存为指定的文件zipAfterFile
- *
- * @param zipBeforeFile 压缩之前的文件
- * @param zipAfterFile 压缩之后的文件
- */
- public void zip(String zipBeforeFile, String zipAfterFile) {
- try {
- ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(mkdirFiles(zipAfterFile)));
- fileZip(zos, new File(zipBeforeFile));
- zos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 解压缩文件unZipBeforeFile保存在unZipAfterFile目录下
- *
- * @param unZipBeforeFile 解压之前的文件
- * @param unZipAfterFile 解压之后的文件
- */
- public void unZip(String unZipBeforeFile, String unZipAfterFile) {
- try {
- ZipInputStream zis = new ZipInputStream(new FileInputStream(unZipBeforeFile));
- File f = new File(unZipAfterFile);
- f.mkdirs();
- fileUnZip(zis, f);
- zis.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
使用AES对文件的加解密:
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.security.Key;
- import java.security.SecureRandom;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- import javax.crypto.spec.SecretKeySpec;
- /**
- * 使用AES对文件进行加密和解密
- *
- */
- public class CipherUtil {
- /**
- * 使用AES对文件进行加密和解密
- *
- */
- private static String type = "AES";
- /**
- * 把文件srcFile加密后存储为destFile
- * @param srcFile 加密前的文件
- * @param destFile 加密后的文件
- * @param privateKey 密钥
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public void encrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {
- Key key = getKey(privateKey);
- Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");
- cipher.init(Cipher.ENCRYPT_MODE, key);
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- fis = new FileInputStream(srcFile);
- fos = new FileOutputStream(mkdirFiles(destFile));
- crypt(fis, fos, cipher);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fis != null) {
- fis.close();
- }
- if (fos != null) {
- fos.close();
- }
- }
- }
- /**
- * 把文件srcFile解密后存储为destFile
- * @param srcFile 解密前的文件
- * @param destFile 解密后的文件
- * @param privateKey 密钥
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public void decrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {
- Key key = getKey(privateKey);
- Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");
- cipher.init(Cipher.DECRYPT_MODE, key);
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- fis = new FileInputStream(srcFile);
- fos = new FileOutputStream(mkdirFiles(destFile));
- crypt(fis, fos, cipher);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fis != null) {
- fis.close();
- }
- if (fos != null) {
- fos.close();
- }
- }
- }
- /**
- * 根据filePath创建相应的目录
- * @param filePath 要创建的文件路经
- * @return file 文件
- * @throws IOException
- */
- private File mkdirFiles(String filePath) throws IOException {
- File file = new File(filePath);
- if (!file.getParentFile().exists()) {
- file.getParentFile().mkdirs();
- }
- file.createNewFile();
- return file;
- }
- /**
- * 生成指定字符串的密钥
- * @param secret 要生成密钥的字符串
- * @return secretKey 生成后的密钥
- * @throws GeneralSecurityException
- */
- private static Key getKey(String secret) throws GeneralSecurityException {
- KeyGenerator kgen = KeyGenerator.getInstance(type);
- kgen.init(128, new SecureRandom(secret.getBytes()));
- SecretKey secretKey = kgen.generateKey();
- return secretKey;
- }
- /**
- * 加密解密流
- * @param in 加密解密前的流
- * @param out 加密解密后的流
- * @param cipher 加密解密
- * @throws IOException
- * @throws GeneralSecurityException
- */
- private static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException {
- int blockSize = cipher.getBlockSize() * 1000;
- int outputSize = cipher.getOutputSize(blockSize);
- byte[] inBytes = new byte[blockSize];
- byte[] outBytes = new byte[outputSize];
- int inLength = 0;
- boolean more = true;
- while (more) {
- inLength = in.read(inBytes);
- if (inLength == blockSize) {
- int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
- out.write(outBytes, 0, outLength);
- } else {
- more = false;
- }
- }
- if (inLength > 0)
- outBytes = cipher.doFinal(inBytes, 0, inLength);
- else
- outBytes = cipher.doFinal();
- out.write(outBytes);
- }
- }
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.security.Key;
- import java.security.SecureRandom;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- import javax.crypto.spec.SecretKeySpec;
- /**
- * 使用AES对文件进行加密和解密
- *
- */
- public class CipherUtil {
- /**
- * 使用AES对文件进行加密和解密
- *
- */
- private static String type = "AES";
- /**
- * 把文件srcFile加密后存储为destFile
- * @param srcFile 加密前的文件
- * @param destFile 加密后的文件
- * @param privateKey 密钥
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public void encrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {
- Key key = getKey(privateKey);
- Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");
- cipher.init(Cipher.ENCRYPT_MODE, key);
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- fis = new FileInputStream(srcFile);
- fos = new FileOutputStream(mkdirFiles(destFile));
- crypt(fis, fos, cipher);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fis != null) {
- fis.close();
- }
- if (fos != null) {
- fos.close();
- }
- }
- }
- /**
- * 把文件srcFile解密后存储为destFile
- * @param srcFile 解密前的文件
- * @param destFile 解密后的文件
- * @param privateKey 密钥
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public void decrypt(String srcFile, String destFile, String privateKey) throws GeneralSecurityException, IOException {
- Key key = getKey(privateKey);
- Cipher cipher = Cipher.getInstance(type + "/ECB/PKCS5Padding");
- cipher.init(Cipher.DECRYPT_MODE, key);
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try {
- fis = new FileInputStream(srcFile);
- fos = new FileOutputStream(mkdirFiles(destFile));
- crypt(fis, fos, cipher);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fis != null) {
- fis.close();
- }
- if (fos != null) {
- fos.close();
- }
- }
- }
- /**
- * 根据filePath创建相应的目录
- * @param filePath 要创建的文件路经
- * @return file 文件
- * @throws IOException
- */
- private File mkdirFiles(String filePath) throws IOException {
- File file = new File(filePath);
- if (!file.getParentFile().exists()) {
- file.getParentFile().mkdirs();
- }
- file.createNewFile();
- return file;
- }
- /**
- * 生成指定字符串的密钥
- * @param secret 要生成密钥的字符串
- * @return secretKey 生成后的密钥
- * @throws GeneralSecurityException
- */
- private static Key getKey(String secret) throws GeneralSecurityException {
- KeyGenerator kgen = KeyGenerator.getInstance(type);
- kgen.init(128, new SecureRandom(secret.getBytes()));
- SecretKey secretKey = kgen.generateKey();
- return secretKey;
- }
- /**
- * 加密解密流
- * @param in 加密解密前的流
- * @param out 加密解密后的流
- * @param cipher 加密解密
- * @throws IOException
- * @throws GeneralSecurityException
- */
- private static void crypt(InputStream in, OutputStream out, Cipher cipher) throws IOException, GeneralSecurityException {
- int blockSize = cipher.getBlockSize() * 1000;
- int outputSize = cipher.getOutputSize(blockSize);
- byte[] inBytes = new byte[blockSize];
- byte[] outBytes = new byte[outputSize];
- int inLength = 0;
- boolean more = true;
- while (more) {
- inLength = in.read(inBytes);
- if (inLength == blockSize) {
- int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
- out.write(outBytes, 0, outLength);
- } else {
- more = false;
- }
- }
- if (inLength > 0)
- outBytes = cipher.doFinal(inBytes, 0, inLength);
- else
- outBytes = cipher.doFinal();
- out.write(outBytes);
- }
- }
对文件或文件夹进行压缩解压加密解密:
- import java.io.File;
- import java.util.UUID;
- public class ZipCipherUtil {
- /**
- * 对目录srcFile下的所有文件目录进行先压缩后加密,然后保存为destfile
- *
- * @param srcFile
- * 要操作的文件或文件夹
- * @param destfile
- * 压缩加密后存放的文件
- * @param keyfile
- * 密钥
- */
- public void encryptZip(String srcFile, String destfile, String keyStr) throws Exception {
- File temp = new File(UUID.randomUUID().toString() + ".zip");
- temp.deleteOnExit();
- // 先压缩文件
- new ZipUtil().zip(srcFile, temp.getAbsolutePath());
- // 对文件加密
- new CipherUtil().encrypt(temp.getAbsolutePath(), destfile, keyStr);
- temp.delete();
- }
- /**
- * 对文件srcfile进行先解密后解压缩,然后解压缩到目录destfile下
- *
- * @param srcfile
- * 要解密和解压缩的文件名
- * @param destfile
- * 解压缩后的目录
- * @param publicKey
- * 密钥
- */
- public void decryptUnzip(String srcfile, String destfile, String keyStr) throws Exception {
- File temp = new File(UUID.randomUUID().toString() + ".zip");
- temp.deleteOnExit();
- // 先对文件解密
- new CipherUtil().decrypt(srcfile, temp.getAbsolutePath(), keyStr);
- // 解压缩
- new ZipUtil().unZip(temp.getAbsolutePath(),destfile);
- temp.delete();
- }
- public static void main(String[] args) throws Exception {
- long l1 = System.currentTimeMillis();
- //加密
- // new ZipCipherUtil().encryptZip("d:\\test\\111.jpg", "d:\\test\\photo.zip", "12345");
- //解密
- new ZipCipherUtil().decryptUnzip("d:\\test\\photo.zip", "d:\\test\\111_1.jpg", "12345");
- long l2 = System.currentTimeMillis();
- System.out.println((l2 - l1) + "毫秒.");
- System.out.println(((l2 - l1) / 1000) + "秒.");
- }
- }
Zip4j(java加密压缩解压文件)使用指南
近期由于项目中的一些需要,花时间来研究了zip4j,目前就介绍这些天研究的成果。主要是介绍:zip4j如何使用,以及一些注意事项。由于网络原因,在中国可能我们无法访问zip4j的官网这样就无法获得它的jar包。而在我研究的项目中添加了Maven支持,所以无需下载此此jar包,只要添加一些配置文件即可。配置文件如下:
- <dependency>
- <groupId>net.lingala.zip4j</groupId>
- <artifactId>zip4j</artifactId>
- <version>1.3.1</version>
- </dependency>
只要将上述代码放置到Maven的pom.xml配置文件中即可,关于Maven的使用我的博客中已经写过类似文章,读者可以查阅与学习。关于zip4j的作用呢!我大概说一下,就是通过在Java项目中对某个文件进行生成压缩包和解压缩的一系列操作,不需要通过第三方工具生成,以及对压缩文件进行加密和解压文件的解密工作。可能最主要的就是减少文件大小和整合文件,在文件下载过程中减少带宽的使用,下面我们开始介绍zip4j的使用:
创建Zip文件,这地方主要涉及其中一个对象:zipFile,以下代码就是创建一个Zip文件:
- try {
- final ZipFile zipFile = new ZipFile("f:\\test\\testZip.zip"); // 創建zip包,指定了zip路徑和zip名稱
- final ArrayList<File> fileAddZip = new ArrayList<File>(); // 向zip包中添加文件集合
- fileAddZip.add(new File("f:\\test\\yangjinhua.doc")); // 向zip包中添加一个word文件
- final ZipParameters parameters = new ZipParameters(); // 设置zip包的一些参数集合
- parameters.setEncryptFiles(true); // 是否设置密码(此处设置为:是)
- parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式(默认值)
- parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 普通级别(参数很多)
- parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密级别
- parameters.setPassword("123456"); // 压缩包密码为123456
- zipFile.createZipFile(fileAddZip, parameters); // 创建压缩包完成
- } catch (final ZipException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
如上代码就可以创建了一个zip文件
解压一个Zip文件,需要需要注意解压前要判断需要解压的zip文件是否存在,以下代码就是解压一个Zip文件:
- try {
- final ZipFile zipFile = new ZipFile("f:\\test\\testZip.zip"); // 根据路径取得需要解压的Zip文件
- if (zipFile.isEncrypted()) { // 判断文件是否加码
- zipFile.setPassword("123456"); // 密码为123456
- }
- zipFile.extractAll("f:\\fffff\\"); // 压缩包文件解压路径
- } catch (final ZipException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
删除一个Zip文件,需要注意文件是否存在,以下代码是善蹴一个Zip文件:
- try {
- final ZipFile zipFile = new ZipFile("f:\\test\\testZip.zip"); // 根据路径取得需要解压的Zip文件
- // 删除压缩文件
- final File file = zipFile.getFile();
- if (file.exists()) { // 判断是否存在
- file.delete();
- }
- } catch (final ZipException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }