當前位置:首頁 » 文件管理 » java把文件夾打包成zip文件

java把文件夾打包成zip文件

發布時間: 2022-10-02 08:12:22

A. 如何用java把內存里的二進制文件打包成ZIP包

Java代碼
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

class ZipTest {
// 壓縮
public static void zip(String zipFileName, String inputFile)
throws Exception {
File f = new File(inputFile);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, f, f.getName());
System.out.println("zip done");
out.close();
}

private static void zip(ZipOutputStream out, File f, String base)
throws Exception {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
in.close();
}

public static void main(String[] args) {
try {
ZipTest t = new ZipTest();
t.zip("c:\\test.zip", "c:\\1.txt");
} catch (Exception e) {
e.printStackTrace(System.out);
}

}
}

B. java怎麼將文件打包成zip包,並且源文件還在,只是多了個zip包,網上多是直接壓縮的,導致源文件不在了

選擇這個添加到壓縮文件,就是保留之前的,多出一份壓縮的啊

C. 誰有把多個文件夾壓縮成zip文件的java方法分享一個

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("d:\\test.zip"));
String test1="test1";
String test2="test2";
byte[] bytes1 = test1.getBytes("UTF-8");
byte[] bytes2 = test2.getBytes("UTF-8");

ZipEntry z1 = new ZipEntry("test1.txt");
zos.putNextEntry(z1);
zos.write(bytes1);
ZipEntry z2 = new ZipEntry("text2.txt");
zos.putNextEntry(z2);
zos.write(bytes2);
zos.closeEntry();
zos.close();

//流可以自己獲取

//java默認的包不支持中文(亂碼)

//使用apache的ZipOutputStream進行zip壓縮

D. java 如何將多個文件打包成一個zip

java 將多個文件打包成一個zip的代碼如下:
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName));
for(int i=0;i<fileList.size();i++){
String filename = (String)fileList.get(i);
File file = new File(filename);
zip(out,file);
}
out.close();

E. java編寫的代碼怎麼壓縮成zip文件

摘要 (1)可以壓縮文件,也可以壓縮文件夾

F. java 如何將多個文件打包成一個zip後進行下載

打包壓縮的如下:
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName));
for(int i=0;i<fileList.size();i++){
String filename = (String)fileList.get(i);
File file = new File(filename);
zip(out,file);
}
out.close();

下載的如下:
private int blockSize=65000;
File file = new File(sourceFilePathName);
FileInputStream fileIn = new FileInputStream(file);
int readBytes = 0;
readBytes = fileIn.read(b, 0, blockSize);
totalRead += readBytes;
out.write(b, 0, readBytes);

代碼大致如此,請參考。

G. 如何用JAVA把內存里的二進制文件打包成ZIP包

在JDK中有一個zip工具類:<blockquote>java.util.zip Provides classes for reading and writing the standard ZIP and
GZIP file formats.</blockquote>使用此類可以將文件夾或者多個文件進行打包壓縮操作。在使用之前先了解關鍵方法:<blockquote>ZipEntry(String name) Creates a new zip entry with the specified name.</blockquote>使用ZipEntry的構造方法可以創建一個zip壓縮文件包的實例,然後通過ZipOutputStream將待壓縮的文件以流的形式寫進該壓縮包中。具體實現代碼如下:<pre t="code" l="java">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.length<1){
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;i<sourceFiles.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 = "file";
boolean flag = FileToZip.fileToZip(sourceFilePath, zipFilePath, fileName);
if(flag){
System.out.println("文件打包成功!");
}else{
System.out.println("文件打包失敗!");
}
}

}

H. 如何使用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 版本問題*/

I. 如何用java 將文件加密壓縮為zip文件.

用java加密壓縮zip文件:
package com.ninemax.demo.zip.decrypt;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.zip.DataFormatException;

import org.apache.commons.io.FileUtils;

import de.idyl.winzipaes.AesZipFileDecrypter;
import de.idyl.winzipaes.AesZipFileEncrypter;
import de.idyl.winzipaes.impl.AESDecrypter;
import de.idyl.winzipaes.impl.AESDecrypterBC;
import de.idyl.winzipaes.impl.AESEncrypter;
import de.idyl.winzipaes.impl.AESEncrypterBC;
import de.idyl.winzipaes.impl.ExtZipEntry;

/**
* 壓縮指定文件或目錄為ZIP格式壓縮文件
* 支持中文(修改源碼後)
* 支持密碼(僅支持256bit的AES加密解密)
* 依賴bcprov項目(bcprov-jdk16-140.jar)
*
* @author zyh
*/
public class DecryptionZipUtil {

/**
* 使用指定密碼將給定文件或文件夾壓縮成指定的輸出ZIP文件
* @param srcFile 需要壓縮的文件或文件夾
* @param destPath 輸出路徑
* @param passwd 壓縮文件使用的密碼
*/
public static void zip(String srcFile,String destPath,String passwd) {
AESEncrypter encrypter = new AESEncrypterBC();
AesZipFileEncrypter zipFileEncrypter = null;
try {
zipFileEncrypter = new AesZipFileEncrypter(destPath, encrypter);
/**
* 此方法是修改源碼後添加,用以支持中文文件名
*/
zipFileEncrypter.setEncoding("utf8");
File sFile = new File(srcFile);
/**
* AesZipFileEncrypter提供了重載的添加Entry的方法,其中:
* add(File f, String passwd)
* 方法是將文件直接添加進壓縮文件
*
* add(File f, String pathForEntry, String passwd)
* 方法是按指定路徑將文件添加進壓縮文件
* pathForEntry - to be used for addition of the file (path within zip file)
*/
doZip(sFile, zipFileEncrypter, "", passwd);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
zipFileEncrypter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 具體壓縮方法,將給定文件添加進壓縮文件中,並處理壓縮文件中的路徑
* @param file 給定磁碟文件(是文件直接添加,是目錄遞歸調用添加)
* @param encrypter AesZipFileEncrypter實例,用於輸出加密ZIP文件
* @param pathForEntry ZIP文件中的路徑
* @param passwd 壓縮密碼
* @throws IOException
*/
private static void doZip(File file, AesZipFileEncrypter encrypter,
String pathForEntry, String passwd) throws IOException {
if (file.isFile()) {
pathForEntry += file.getName();
encrypter.add(file, pathForEntry, passwd);
return;
}
pathForEntry += file.getName() + File.separator;
for(File subFile : file.listFiles()) {
doZip(subFile, encrypter, pathForEntry, passwd);
}
}

/**
* 使用給定密碼解壓指定壓縮文件到指定目錄
* @param inFile 指定Zip文件
* @param outDir 解壓目錄
* @param passwd 解壓密碼
*/
public static void unzip(String inFile, String outDir, String passwd) {
File outDirectory = new File(outDir);
if (!outDirectory.exists()) {
outDirectory.mkdir();
}
AESDecrypter decrypter = new AESDecrypterBC();
AesZipFileDecrypter zipDecrypter = null;
try {
zipDecrypter = new AesZipFileDecrypter(new File(inFile), decrypter);
AesZipFileDecrypter.charset = "utf-8";
/**
* 得到ZIP文件中所有Entry,但此處好像與JDK里不同,目錄不視為Entry
* 需要創建文件夾,entry.isDirectory()方法同樣不適用,不知道是不是自己使用錯誤
* 處理文件夾問題處理可能不太好
*/
List<ExtZipEntry> entryList = zipDecrypter.getEntryList();
for(ExtZipEntry entry : entryList) {
String eName = entry.getName();
String dir = eName.substring(0, eName.lastIndexOf(File.separator) + 1);
File extractDir = new File(outDir, dir);
if (!extractDir.exists()) {
FileUtils.forceMkdir(extractDir);
}
/**
* 抽出文件
*/
File extractFile = new File(outDir + File.separator + eName);
zipDecrypter.extractEntry(entry, extractFile, passwd);
}
} catch (IOException e) {
e.printStackTrace();
} catch (DataFormatException e) {
e.printStackTrace();
} finally {
try {
zipDecrypter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 測試
* @param args
*/
public static void main(String[] args) {
/**
* 壓縮測試
* 可以傳文件或者目錄
*/
// zip("M:\\ZIP\\test\\bb\\a\\t.txt", "M:\\ZIP\\test\\temp1.zip", "zyh");
// zip("M:\\ZIP\\test\\bb", "M:\\ZIP\\test\\temp2.zip", "zyh");

unzip("M:\\ZIP\\test\\temp2.zip", "M:\\ZIP\\test\\temp", "zyh");
}
}
壓縮多個文件時,有兩個方法(第一種沒試):
(1) 預先把多個文件壓縮成zip,然後調用enc.addAll(inZipFile, password);方法將多個zip文件加進來。
(2)針對需要壓縮的文件循環調用enc.add(inFile, password);,每次都用相同的密碼。

J. 怎樣用Java生成ZIP文件

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;


import org.apache.tools.zip.ZipEntry;

import org.apache.tools.zip.ZipOutputStream;


/**

* @project: Test

* @author chenssy

* @date 2013-7-28

* @Description: 文件壓縮工具類

* 將指定文件/文件夾壓縮成zip、rar壓縮文件

*/

public class CompressedFileUtil {

/**

* 默認構造函數

*/

public CompressedFileUtil(){

}


/**

* @desc 將源文件/文件夾生成指定格式的壓縮文件,格式zip

* @param resourePath 源文件/文件夾

* @param targetPath 目的壓縮文件保存路徑

* @return void

* @throws Exception

*/

public void compressedFile(String resourcesPath,String targetPath) throws Exception{

File resourcesFile = new File(resourcesPath); //源文件

File targetFile = new File(targetPath); //目的

//如果目的路徑不存在,則新建

if(!targetFile.exists()){

targetFile.mkdirs();

}

String targetName = resourcesFile.getName()+".zip"; //目的壓縮文件名

FileOutputStream outputStream = new FileOutputStream(targetPath+"\"+targetName);

ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));

createCompressedFile(out, resourcesFile, "");

out.close();

}

/**

* @desc 生成壓縮文件。

* 如果是文件夾,則使用遞歸,進行文件遍歷、壓縮

* 如果是文件,直接壓縮

* @param out 輸出流

* @param file 目標文件

* @return void

* @throws Exception

*/

public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{

//如果當前的是文件夾,則進行進一步處理

if(file.isDirectory()){

//得到文件列表信息

File[] files = file.listFiles();

//將文件夾添加到下一級打包目錄

out.putNextEntry(new ZipEntry(dir+"/"));

dir = dir.length() == 0 ? "" : dir +"/";

//循環將文件夾中的文件打包

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

createCompressedFile(out, files[i], dir + files[i].getName()); //遞歸處理

}

}

else{ //當前的是文件,打包處理

//文件輸入流

FileInputStream fis = new FileInputStream(file);

out.putNextEntry(new ZipEntry(dir));

//進行寫操作

int j = 0;

byte[] buffer = new byte[1024];

while((j = fis.read(buffer)) > 0){

out.write(buffer,0,j);

}

//關閉輸入流

fis.close();

}

}

public static void main(String[] args){

CompressedFileUtil compressedFileUtil = new CompressedFileUtil();

try {

compressedFileUtil.compressedFile("G:\zip", "F:\zip");

System.out.println("壓縮文件已經生成...");

} catch (Exception e) {

System.out.println("壓縮文件生成失敗...");

e.printStackTrace();

}

}

}

運行程序結果如下:

如果是使用java.util下的java.util.zip進行打包處理,可能會出現中文亂碼問題,這是因為java的zip方法不支持編碼格式的更改,我們可以使用ant.java下的zip工具類來進行打包處理。所以需要將ant.jar導入項目的lib目錄下。

熱點內容
榮威i6max配置怎麼選 發布:2024-03-28 16:18:11 瀏覽:454
cml編程 發布:2024-03-28 16:14:53 瀏覽:757
linuxc語言文件讀寫 發布:2024-03-28 15:59:57 瀏覽:578
點遍歷演算法 發布:2024-03-28 15:57:34 瀏覽:496
java網路框架 發布:2024-03-28 15:42:07 瀏覽:98
我的世界本地部署伺服器 發布:2024-03-28 15:40:55 瀏覽:166
電腦代理伺服器認證 發布:2024-03-28 15:19:17 瀏覽:409
sql查詢當天數據 發布:2024-03-28 14:45:19 瀏覽:299
phpapi圖片 發布:2024-03-28 14:28:56 瀏覽:616
編程趣味 發布:2024-03-28 14:20:52 瀏覽:972