「java创建压缩文件」java添加文件到压缩包

博主:adminadmin 2023-01-07 15:36:07 1071

本篇文章给大家谈谈java创建压缩文件,以及java添加文件到压缩包对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

如何使用java压缩文件夹成为zip包

在JDK中有一个zip工具类:

java.util.zip    Provides classes for reading and writing the standard ZIP and

GZIP file formats.

使用此类可以将文件夹或者多个文件进行打包压缩操作。

在使用之前先了解关键方法:

ZipEntry(String name)         Creates a new zip entry with the specified name.

使用ZipEntry的构造方法可以创建一个zip压缩文件包的实例,然后通过ZipOutputStream将待压缩的文件以流的形式写进该压缩包中。具体实现代码如下:

import java.io.BufferedInputStream;  

import java.io.BufferedOutputStream;  

import java.io.File;  

import java.io.FileInputStream;  

import java.io.FileNotFoundException;  

import java.io.FileOutputStream;  

import java.io.IOException;  

import java.util.zip.ZipEntry;  

import java.util.zip.ZipOutputStream;  

/** 

 * 将文件夹下面的文件 

 * 打包成zip压缩文件 

 *  

 * @author admin 

 * 

 */  

public final class FileToZip {  

  

    private FileToZip(){}  

      

    /** 

     * 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下 

     * @param sourceFilePath :待压缩的文件路径 

     * @param zipFilePath :压缩后存放路径 

     * @param fileName :压缩后文件的名称 

     * @return 

     */  

    public static boolean fileToZip(String sourceFilePath,String zipFilePath,String fileName){  

        boolean flag = false;  

        File sourceFile = new File(sourceFilePath);  

        FileInputStream fis = null;  

        BufferedInputStream bis = null;  

        FileOutputStream fos = null;  

        ZipOutputStream zos = null;  

          

        if(sourceFile.exists() == false){  

            System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");  

        }else{  

            try {  

                File zipFile = new File(zipFilePath + "/" + fileName +".zip");  

                if(zipFile.exists()){  

                    System.out.println(zipFilePath + "目录下存在名字为:" + fileName +".zip" +"打包文件.");  

                }else{  

                    File[] sourceFiles = sourceFile.listFiles();  

                    if(null == sourceFiles || sourceFiles.length1){  

                        System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");  

                    }else{  

                        fos = new FileOutputStream(zipFile);  

                        zos = new ZipOutputStream(new BufferedOutputStream(fos));  

                        byte[] bufs = new byte[1024*10];  

                        for(int i=0;isourceFiles.length;i++){  

                            //创建ZIP实体,并添加进压缩包  

                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());  

                            zos.putNextEntry(zipEntry);  

                            //读取待压缩的文件并写进压缩包里  

                            fis = new FileInputStream(sourceFiles[i]);  

                            bis = new BufferedInputStream(fis, 1024*10);  

                            int read = 0;  

                            while((read=bis.read(bufs, 0, 1024*10)) != -1){  

                                zos.write(bufs,0,read);  

                            }  

                        }  

                        flag = true;  

                    }  

                }  

            } catch (FileNotFoundException e) {  

                e.printStackTrace();  

                throw new RuntimeException(e);  

            } catch (IOException e) {  

                e.printStackTrace();  

                throw new RuntimeException(e);  

            } finally{  

                //关闭流  

                try {  

                    if(null != bis) bis.close();  

                    if(null != zos) zos.close();  

                } catch (IOException e) {  

                    e.printStackTrace();  

                    throw new RuntimeException(e);  

                }  

            }  

        }  

        return flag;  

    }  

      

    public static void main(String[] args){  

        String sourceFilePath = "D:\\TestFile";  

        String zipFilePath = "D:\\tmp";  

        String fileName = "12700153file";  

        boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);  

        if(flag){  

            System.out.println("文件打包成功!");  

        }else{  

            System.out.println("文件打包失败!");  

        }  

    }  

      

}

搭建Java环境如何解压缩

具体解压缩方法如下:

Java压缩解压缩文件的方法有,第一中借助javajdk自带的ZipOutputStream和ZipInputStream。第二种,借助第三方jar,例如ApacheCommonsCompress和Ant。

前提,需要将Ant的ant、jar和ant-launcher、jar添加到classpath中。先创建一个Expander类,该类继承了Ant的org、apache、tools、ant、taskdefs、Expand类。

第二步:使用Expander类。

如何使用JAVA代码压缩PDF文件

用java代码压缩应用到程序了,代码一般是比较复杂的,对pdf文件的mate标签优化,这类标签包括三类,pdf文件不是网页就是个文件,何况我们可以用pdf压缩工具压缩,下面有个解决方法,楼主可以做参照。

1:点击打开工具,打开主页面上有三个功能进行选择,我们选择pdf文件压缩。

2:这这个页面中我们选择pdf文件在这里打开,点击“添加文件”按钮将文件添加进来。

3:然后在页面中点击“开始压缩”就可以开始压缩文件了。

4:压缩完成的文件页面会显示已经完成。

java多线程压缩文件

/**

 * 递归压缩文件夹

 * 

 * @param srcRootDir

 *            压缩文件夹根目录的子路径

 * @param file

 *            当前递归压缩的文件或目录对象

 * @param zos

 *            压缩文件存储对象

 * @throws Exception

 */

private static void zip(String srcRootDir, File file, ZipOutputStream zos) throws Exception {

if (file == null) {

return;

}

// 如果是文件,则直接压缩该文件

if (file.isFile()) {

int count, bufferLen = 1024;

byte data[] = new byte[bufferLen];

// 获取文件相对于压缩文件夹根目录的子路径

String subPath = file.getAbsolutePath();

int index = subPath.indexOf(srcRootDir);

if (index != -1) {

subPath = subPath.substring(srcRootDir.length() + File.separator.length());

}

ZipEntry entry = new ZipEntry(subPath);

zos.putNextEntry(entry);

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

while ((count = bis.read(data, 0, bufferLen)) != -1) {

zos.write(data, 0, count);

}

bis.close();

zos.closeEntry();

}

// 如果是目录,则压缩整个目录

else {

// 压缩目录中的文件或子目录

File[] childFileList = file.listFiles();

for (int n = 0; n  childFileList.length; n++) {

childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());

zip(srcRootDir, childFileList[n], zos);

}

}

}

/**

 * 对文件或文件目录进行压缩

 * 

 * @param srcPath

 *            要压缩的源文件路径。如果压缩一个文件,则为该文件的全路径;如果压缩一个目录,则为该目录的顶层目录路径

 * @param zipPath

 *            压缩文件保存的路径。注意:zipPath不能是srcPath路径下的子文件夹

 * @param zipFileName

 *            压缩文件名

 * @throws Exception

 */

public static void zip(String srcPath, String zipPath, String zipFileName) throws Exception {

if (StringUtils.isEmpty(srcPath) || StringUtils.isEmpty(zipPath) || StringUtils.isEmpty(zipFileName)) {

return;

// throw new

// ParameterException(ICommonResultCode.PARAMETER_IS_NULL);

}

CheckedOutputStream cos = null;

ZipOutputStream zos = null;

try {

File srcFile = new File(srcPath);

// 判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)

if (srcFile.isDirectory()  zipPath.indexOf(srcPath) != -1) {

return;

// throw new

// ParameterException(ICommonResultCode.INVALID_PARAMETER,

// "zipPath must not be the child directory of srcPath.");

}

// 判断压缩文件保存的路径是否存在,如果不存在,则创建目录

File zipDir = new File(zipPath);

if (!zipDir.exists() || !zipDir.isDirectory()) {

zipDir.mkdirs();

}

// 创建压缩文件保存的文件对象

String zipFilePath = zipPath + File.separator + zipFileName;

File zipFile = new File(zipFilePath);

if (zipFile.exists()) {

// 检测文件是否允许删除,如果不允许删除,将会抛出SecurityException

SecurityManager securityManager = new SecurityManager();

securityManager.checkDelete(zipFilePath);

// 删除已存在的目标文件

zipFile.delete();

}

cos = new CheckedOutputStream(new FileOutputStream(zipFile), new CRC32());

zos = new ZipOutputStream(cos);

// 如果只是压缩一个文件,则需要截取该文件的父目录

String srcRootDir = srcPath;

if (srcFile.isFile()) {

int index = srcPath.lastIndexOf(File.separator);

if (index != -1) {

srcRootDir = srcPath.substring(0, index);

}

}

// 调用递归压缩方法进行目录或文件压缩

zip(srcRootDir, srcFile, zos);

zos.flush();

} catch (Exception e) {

throw e;

} finally {

try {

if (zos != null) {

zos.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

如何使用java压缩文件夹成为zip包(最简单的

import java.io.File;

public class ZipCompressorByAnt {

private File zipFile;

/**

* 压缩文件构造函数

* @param pathName 最终压缩生成的压缩文件:目录+压缩文件名.zip

*/

public ZipCompressorByAnt(String finalFile) {

zipFile = new File(finalFile);

}

/**

* 执行压缩操作

* @param srcPathName 需要被压缩的文件/文件夹

*/

public void compressExe(String srcPathName) {

System.out.println("srcPathName="+srcPathName);

File srcdir = new File(srcPathName);

if (!srcdir.exists()){

throw new RuntimeException(srcPathName + "不存在!");

}

Project prj = new Project();

Zip zip = new Zip();

zip.setProject(prj);

zip.setDestFile(zipFile);

FileSet fileSet = new FileSet();

fileSet.setProject(prj);

fileSet.setDir(srcdir);

//fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");

//fileSet.setExcludes(...); //排除哪些文件或文件夹

zip.addFileset(fileSet);

zip.execute();

}    

}

public class TestZip {

public static void main(String[] args) {

ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\test1.zip ");

zca.compressExe("E:\\test1");

}  

}

/*如果 出现ant 的 52  51 50 等版本问题 可以去找对应的ant-1.8.2.jar     我开始用的ant-1.10.1.jar 就是这个包版本高了  一直报verson 52 版本问题*/

java创建压缩文件的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java添加文件到压缩包、java创建压缩文件的信息别忘了在本站进行查找喔。