用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);,每次都用相同的密碼。
B. java ZipOutputStream 壓縮包裡面壓縮多個文件(格式為zip文件)
在壓縮包里運行文件都是制動解壓到臨時文件夾臨時文件夾在C盤所以還是建議正常解壓後再運行在有些情況下直接在壓縮包里運行文件有些程序還未解壓到臨時文件夾所以就會報錯手動解壓在運行是最好的以,下是臨時文件夾的路徑
C:\Documents and Settings\Administrator\Local Settings\Temp
C. java如何實現多個文件的壓縮
importjava.util.*;
importjava.net.URI;
importjava.nio.file.Path;
importjava.nio.file.*;
publicclassZipFSPUser{
publicstaticvoidmain(String[]args)throwsThrowable{
Map<String,String>env=newHashMap<>();
env.put("create","true");
//
//definedinjava.net.JarURLConnection
URIuri=URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try(FileSystemzipfs=FileSystems.newFileSystem(uri,env)){
PathexternalTxtFile=Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
PathpathInZipfile=zipfs.getPath("/SomeTextFile.txt");
//afileintothezipfile
Files.(externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING);
}
}
}
創建一個zip文件,並添加一個文件進去,需要JDK7
D. java中將一個文件夾下所有的文件壓縮成一個文件,然後,解壓到指定目錄.
import java.io.*;
import java.util.zip.*;
public class CompressD {
// 緩沖
static byte[] buffer = new byte[2048];
public static void main(String[] args) throws Exception {
// 來源
File inputDir = new File("C:\\CompressTest\\");
// 目標
FileOutputStream fos = new FileOutputStream("C:\\CompressTest.zip");
// 過濾
ZipOutputStream zos = new ZipOutputStream(fos);
// 壓縮
zip(inputDir.listFiles(), "", zos);
// 關閉
zos.close();
}
private static void zip(File[] files, String baseFolder, ZipOutputStream zos)
throws Exception {
// 輸入
FileInputStream fis = null;
// 條目
ZipEntry entry = null;
// 數目
int count = 0;
for (File file : files) {
if (file.isDirectory()) {
// 遞歸
zip(file.listFiles(), file.getName() + File.separator, zos);
continue;
}
entry = new ZipEntry(baseFolder + file.getName());
// 加入
zos.putNextEntry(entry);
fis = new FileInputStream(file);
// 讀取
while ((count = fis.read(buffer, 0, buffer.length)) != -1)
// 寫入
zos.write(buffer, 0, count);
}
}
}
E. 在java中,gzip 壓縮和解壓多個文件
直接編譯運行!!!
不知道你是要查看壓縮文件還是要解壓文件,所以發上來兩個。
第一個可以查看各個壓縮項目;
第二個可以解壓文件。
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
class ZipTest {
public static void main(String[] args) {
ZipTestFrame frame = new ZipTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ZipTestFrame extends JFrame {
private JComboBox fileCombo;
private JTextArea fileText;
private String zipname;
public ZipTestFrame() {
setTitle("ZipTest");
setSize(400,300);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem);
openItem.addActionListener(new OpenAction());
JMenuItem exitItem = new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menuBar.add(menu);
setJMenuBar(menuBar);
fileText = new JTextArea();
fileCombo = new JComboBox();
fileCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadZipFile((String)fileCombo.getSelectedItem());
}
});
add(fileCombo, BorderLayout.SOUTH);
add(new JScrollPane(fileText), BorderLayout.CENTER);
}
public class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
ExtensionFileFilter filter = new ExtensionFileFilter();
filter.addExtension(".zip");
filter.addExtension(".jar");
filter.setDescription("ZIP archives");
chooser.setFileFilter(filter);
int r = chooser.showOpenDialog(ZipTestFrame.this);
if(r == JFileChooser.APPROVE_OPTION) {
zipname = chooser.getSelectedFile().getPath();
scanZipFile();
}
}
}
public void scanZipFile() {
fileCombo.removeAllItems();
try {
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
ZipEntry entry;
while((entry = zin.getNextEntry()) != null) {
fileCombo.addItem(entry.getName());
zin.closeEntry();
}
zin.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public void loadZipFile(String name) {
try {
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
ZipEntry entry;
fileText.setText("");
while((entry = zin.getNextEntry()) != null) {
if(entry.getName().equals(name)) {
BufferedReader in = new BufferedReader(new InputStreamReader(zin));
String line;
while((line = in.readLine())!=null) {
fileText.append(line);
fileText.append("\n");
}
}
zin.closeEntry();
}
zin.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
class ExtensionFileFilter extends FileFilter {
private String description = "";
private ArrayList<String>extensions = new ArrayList<String>();
public void addExtension(String extension) {
if(!extension.startsWith("."))
extension = "." + extension;
extensions.add(extension.toLowerCase());
}
public void setDescription(String aDescription) {
description = aDescription;
}
public String getDescription() {
return description;
}
public boolean accept(File f) {
if(f.isDirectory()) return true;
String name = f.getName().toLowerCase();
for(String e : extensions)
if(name.endsWith(e))
return true;
return false;
}
}
///////////////////////////////////////////////////////////
/**
*類名:zipFileRelease
*說明:一個zip文件解壓類
*介紹:主要的zip文件釋放方法releaseHandle()
* 用ZipInputStream類和ZipEntry類將zip文件的入口清單列舉出來,然後
* 根據用戶提供的輸出路徑和zip文件的入口進行組合通過DataOutputStream
* 和File類進行文件的創建和目錄的創建,創建文件時的文件數據是通過
* ZipInputStream類、ZipEntry類、InputStream類之間的套嵌組合獲得的。
*注意:如果zip文件中包含中文路徑程序將會拋出異常
*/
import java.io.*;
import java.util.*;
import java.util.zip.*;
class zipFileRelease{
private String inFilePath;
private String releaseFilePath;
private String[] FileNameArray; //存放文件名稱的數組
private ZipEntry entry;
//
private FileInputStream fileDataIn;
private FileOutputStream fileDataOut;
private ZipInputStream zipInFile;
private DataOutputStream writeData;
private DataInputStream readData;
//
private int zipFileCount = 0; //zip文件中的文件總數
private int zipPathCount = 0; //zip文件中的路徑總數
/**
*初始化函數
*初始化zip文件流、輸出文件流以及其他變數的初始化
*/
public zipFileRelease(String inpath,String releasepath){
inFilePath = inpath;
releaseFilePath = releasepath;
}
/**
*初始化讀取文件流函數
*參數:FileInputStream類
*返回值:初始化成功返回0,否則返回-1
*/
protected long initInStream(ZipInputStream zipFileA){
try{
readData = new DataInputStream(zipFileA);
return 0;
}catch(Exception e){
e.printStackTrace();
return -1;
}
}
/**
*測試文件路徑
*參數:zip文件的路徑和要釋放的位置
*返回值:是兩位整數,兩位數中的十位代表輸入路徑和輸出路徑(1輸入、2輸出)
* 各位數是代表絕對路徑還是相對路徑(1絕對、0相對)
* 返回-1表示路徑無效
protected long checkPath(String inPath,String outPath){
File infile = new File(inPath);
File infile = new File(outPath);
}
*/
/**
*初始化輸出文件流
*參數:File類
*返回值:初始化成功返回0,否則返回-1
*/
protected long initOutStream(String outFileA){
try{
fileDataOut = new FileOutputStream(outFileA);
writeData = new DataOutputStream(fileDataOut);
return 0;
}catch(IOException e){
e.printStackTrace();
return -1;
}
}
/**
*測試文件是否存在方法
*參數:File類
*返回值:如果文件存在返迴文件大小,否則返回-1
*/
public long checkFile(File inFileA){
if (inFileA.exists()){
return 0;
}else{
return -1;
}
}
/**
*判斷文件是否可以讀取方法
*參數:File類
*返回值:如果可以讀取返回0,否則返回-1
*/
public long checkOpen(File inFileA){
if(inFileA.canRead()){
return inFileA.length();
}else{
return -1;
}
}
/**
*獲得zip文件中的文件夾和文件總數
*參數:File類
*返回值:如果正常獲得則返回總數,否則返回-1
*/
public long getFilFoldCount(String infileA){
try{
int fileCount = 0;
zipInFile = new ZipInputStream(new FileInputStream(infileA));
while ((entry = zipInFile.getNextEntry()) != null){
if (entry.isDirectory()){
zipPathCount++;
}else{
zipFileCount++;
}
fileCount++;
}
return fileCount;
}catch(IOException e){
e.printStackTrace();
return -1;
}
}
/**
*讀取zip文件清單函數
*參數:File類
*返回值:文件清單數組
*/
public String[] getFileList(String infileA){
try{
ZipInputStream AzipInFile = new ZipInputStream(new FileInputStream(infileA));
//創建數組對象
FileNameArray = new String[(int)getFilFoldCount(infileA)];
//將文件名清單傳入數組
int i = 0;
while ((entry = AzipInFile.getNextEntry()) != null){
FileNameArray[i++] = entry.getName();
}
return FileNameArray;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
/**
*創建文件函數
*參數:File類
*返回值:如果創建成功返回0,否則返回-1
*/
public long writeFile(String outFileA,byte[] dataByte){
try{
if (initOutStream(outFileA) == 0){
writeData.write(dataByte);
fileDataOut.close();
return 0;
}else{
fileDataOut.close();
return -1;
}
}catch(IOException e){
e.printStackTrace();
return -1;
}
}
/**
*讀取文件內容函數
*參數:File類
*返回值:如果讀取成功則返回讀取數據的位元組數組,如果失敗則返回空值
*/
protected byte[] readFile(ZipEntry entryA,ZipInputStream zipFileA){
try{
long entryFilelen;
if (initInStream(zipFileA) == 0){
if ((entryFilelen = entryA.getSize()) >= 0){
byte[] entryFileData = new byte[(int)entryFilelen];
readData.readFully(entryFileData,0,(int)entryFilelen);
return entryFileData;
}else{
return null;
}
}else{
return null;
}
}catch(IOException e){
e.printStackTrace();
return null;
}
}
/**
*創建目錄函數
*參數:要創建目錄的路徑
*返回值:如果創建成功則返回0,否則返回-1
*/
public long createFolder(String dir){
File file = new File(dir);
if (file.mkdirs()) {
return 0;
}else{
return -1;
}
}
/**
*刪除文件
*參數:要刪除的文件
*返回值:如果刪除成功則返回0,要刪除的文件不存在返回-2
* 如果要刪除的是個路徑則返回-3,刪除失敗則返回-1
*/
public long deleteFile(String Apath) throws SecurityException {
File file = new File(Apath.trim());
//文件或路徑不存在
if (!file.exists()){
return -2;
}
//要刪除的是個路徑
if (!file.isFile()){
return -3;
}
//刪除
if (file.delete()){
return 0;
}else{
return -1;
}
}
/**
*刪除目錄
*參數:要刪除的目錄
*返回值:如果刪除成功則返回0,刪除失敗則返回-1
*/
public long deleteFolder(String Apath){
File file = new File(Apath);
//刪除
if (file.delete()){
return 0;
}else{
return -1;
}
}
/**
*判斷所要解壓的路徑是否存在同名文件
*參數:解壓路徑
*返回值:如果存在同名文件返回-1,否則返回0
*/
public long checkPathExists(String AreleasePath){
File file = new File(AreleasePath);
if (!file.exists()){
return 0;
}else{
return -1;
}
}
/**
*刪除zip中的文件
*參數:文件清單數組,釋放路徑
*返回值:如果刪除成功返回0,否則返回-1
*/
protected long deleteReleaseZipFile(String[] listFilePath,String releasePath){
long arrayLen,flagReturn;
int k = 0;
String tempPath;
//存放zip文件清單的路徑
String[] pathArray = new String[zipPathCount];
//刪除文件
arrayLen = listFilePath.length;
for(int i=0;i<(int)arrayLen;i++){
tempPath = releasePath.replace('\\','/') + listFilePath[i];
flagReturn = deleteFile(tempPath);
if (flagReturn == -2){
//什麼都不作
}else if (flagReturn == -3){
pathArray[k++] = tempPath;
}else if (flagReturn == -1){
return -1;
}
}
//刪除路徑
for(k = k - 1;k>=0;k--){
flagReturn = deleteFolder(pathArray[k]);
if (flagReturn == -1) return -1;
}
return 0;
}
/**
*獲得zip文件的最上層的文件夾名稱
*參數:zip文件路徑
*返回值:文件夾名稱,如果失敗則返回null
*/
public String getZipRoot(String infileA){
String rootName;
try{
FileInputStream tempfile = new FileInputStream(infileA);
ZipInputStream AzipInFile = new ZipInputStream(tempfile);
ZipEntry Aentry;
Aentry = AzipInFile.getNextEntry();
rootName = Aentry.getName();
tempfile.close();
AzipInFile.close();
return rootName;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
/**
*釋放流,釋放佔用資源
*/
protected void closeStream() throws Exception{
fileDataIn.close();
fileDataOut.close();
zipInFile.close();
writeData.flush();
}
/**
*解壓函數
*對用戶的zip文件路徑和解壓路徑進行判斷,是否存在和打開
*在輸入解壓路徑時如果輸入"/"則在和zip文件存放的統計目錄下進行解壓
*返回值:0表示釋放成功
* -1 表示您所要解壓的文件不存在、
* -2表示您所要解壓的文件不能被打開、
* -3您所要釋放的路徑不存在、
* -4您所創建文件目錄失敗、
* -5寫入文件失敗、
* -6表示所要釋放的文件已經存在、
* -50表示文件讀取異常
*/
public long releaseHandle() throws Exception{
File inFile = new File(inFilePath);
File outFile = new File(releaseFilePath);
String tempFile;
String zipPath;
String zipRootPath;
String tempPathParent; //存放釋放路徑
byte[] zipEntryFileData;
//作有效性判斷
if (checkFile(inFile) == -1) {
return -1;}
if (checkOpen(inFile) == -1) {
return -2;}
//不是解壓再當前目錄下時對路徑作有效性檢驗
if (!releaseFilePath.equals("/")){
//解壓在用戶指定目錄下
if (checkFile(outFile) == -1) {
return -3;}
}
//獲得標准釋放路徑
if (!releaseFilePath.equals("/")) {
tempPathParent = releaseFilePath.replace('\\','/')+ "/";
}else{
tempPathParent = inFile.getParent().replace('\\','/')+ "/";
}
//獲得zip文件中的入口清單
FileNameArray = getFileList(inFilePath);
//獲得zip文件的最上層目錄
zipRootPath = getZipRoot(inFilePath);
//
fileDataIn = new FileInputStream(inFilePath);
zipInFile = new ZipInputStream(fileDataIn);
//判斷是否已經存在要釋放的文件夾
if (zipRootPath.lastIndexOf("/") > 0 ){
if (checkPathExists(tempPathParent +
zipRootPath.substring(0,zipRootPath.lastIndexOf("/"))) == -1){
return -6;
}
}else{
if (checkPathExists(tempPathParent + zipRootPath) == -1){
return -6;
}
}
//
try{
//創建文件夾和文件
int i = 0;
while ((entry = zipInFile.getNextEntry()) != null){
if (entry.isDirectory()){
//創建目錄
zipPath = tempPathParent + FileNameArray[i];
zipPath = zipPath.substring(0,zipPath.lastIndexOf("/"));
if (createFolder(zipPath) == -1){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
return -4;
}
}else{
//讀取文件數據
zipEntryFileData = readFile(entry,zipInFile);
//向文件寫數據
tempFile = tempPathParent + FileNameArray[i];
//寫入文件
if (writeFile(tempFile,zipEntryFileData) == -1){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
return -5;
}
}
i++;
}
//釋放資源
closeStream();
return 0;
}catch(Exception e){
closeStream();
deleteReleaseZipFile(FileNameArray,tempPathParent);
e.printStackTrace();
return -50;
}
}
/**
*演示函數
*根據用戶輸入的路徑對文件進行解壓
*/
public static void main(String args[]) throws Exception {
long flag; //返回標志
String inPath,releasePath;
//獲得用戶輸入信息
BufferedReader userInput = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("請輸入zip文件路徑:");
inPath = userInput.readLine();
System.out.println("請輸入保存路徑:");
releasePath = userInput.readLine();
userInput.close();
//執行解壓縮
zipFileRelease pceraZip = new zipFileRelease(inPath,releasePath);
flag = pceraZip.releaseHandle();
//出錯信息列印
if (flag == 0) System.out.println("釋放成功!!!");
if (flag == -1) System.out.println("您所要解壓的文件不存在!");
if (flag == -2) System.out.println("您所要解壓的文件不能被打開!");
if (flag == -3) System.out.println("您所要釋放的路徑不存在!");
if (flag == -4) System.out.println("您所創建文件目錄失敗!");
if (flag == -5) System.out.println("寫入文件失敗!");
if (flag == -6) System.out.println("文件已經存在!");
if (flag == -50) System.out.println("文件讀取異常!");
}
}
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. 誰有把多個文件夾壓縮成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壓縮
H. 如何用zip把一個文件壓縮成多個壓縮包
1、准備好自己需要分卷壓縮的文件,安裝壓縮軟體,WinRAR、好壓等等。
2、使用滑鼠右鍵點擊將要被分卷壓縮的文件,然後選擇「添加到壓縮文件」,進行文件的壓縮。
3、類似的壓縮軟體操作差不多,都是選擇自定義之類的進行分區壓縮的大小設定。
選擇「自定義」。
4、在「壓縮分卷大小」中選擇一個合適的大小,比如2M等等,然後還可以選擇一下壓縮所使用的格式。
5、點擊「立即壓縮」開始分卷壓縮了。
I. 怎樣用java快速實現zip文件的壓縮解壓縮
packagezip;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.util.Enumeration;
importjava.util.zip.CRC32;
importjava.util.zip.CheckedOutputStream;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipFile;
importjava.util.zip.ZipOutputStream;
importorg.apache.commons.lang3.StringUtils;
publicclassZipUtil{
/**
*遞歸壓縮文件夾
*@paramsrcRootDir壓縮文件夾根目錄的子路徑
*@paramfile當前遞歸壓縮的文件或目錄對象
*@paramzos壓縮文件存儲對象
*@throwsException
*/
privatestaticvoidzip(StringsrcRootDir,Filefile,ZipOutputStreamzos)throwsException
{
if(file==null)
{
return;
}
//如果是文件,則直接壓縮該文件
if(file.isFile())
{
intcount,bufferLen=1024;
bytedata[]=newbyte[bufferLen];
//獲取文件相對於壓縮文件夾根目錄的子路徑
StringsubPath=file.getAbsolutePath();
intindex=subPath.indexOf(srcRootDir);
if(index!=-1)
{
subPath=subPath.substring(srcRootDir.length()+File.separator.length());
}
ZipEntryentry=newZipEntry(subPath);
zos.putNextEntry(entry);
BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file));
while((count=bis.read(data,0,bufferLen))!=-1)
{
zos.write(data,0,count);
}
bis.close();
zos.closeEntry();
}
//如果是目錄,則壓縮整個目錄
else
{
//壓縮目錄中的文件或子目錄
File[]childFileList=file.listFiles();
for(intn=0;n<childFileList.length;n++)
{
childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());
zip(srcRootDir,childFileList[n],zos);
}
}
}
/**
*對文件或文件目錄進行壓縮
*@paramsrcPath要壓縮的源文件路徑。如果壓縮一個文件,則為該文件的全路徑;如果壓縮一個目錄,則為該目錄的頂層目錄路徑
*@paramzipPath壓縮文件保存的路徑。注意:zipPath不能是srcPath路徑下的子文件夾
*@paramzipFileName壓縮文件名
*@throwsException
*/
publicstaticvoidzip(StringsrcPath,StringzipPath,StringzipFileName)throwsException
{
if(StringUtils.isEmpty(srcPath)||StringUtils.isEmpty(zipPath)||StringUtils.isEmpty(zipFileName))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
CheckedOutputStreamcos=null;
ZipOutputStreamzos=null;
try
{
FilesrcFile=newFile(srcPath);
//判斷壓縮文件保存的路徑是否為源文件路徑的子文件夾,如果是,則拋出異常(防止無限遞歸壓縮的發生)
if(srcFile.isDirectory()&&zipPath.indexOf(srcPath)!=-1)
{
thrownewParameterException(ICommonResultCode.INVALID_PARAMETER,".");
}
//判斷壓縮文件保存的路徑是否存在,如果不存在,則創建目錄
FilezipDir=newFile(zipPath);
if(!zipDir.exists()||!zipDir.isDirectory())
{
zipDir.mkdirs();
}
//創建壓縮文件保存的文件對象
StringzipFilePath=zipPath+File.separator+zipFileName;
FilezipFile=newFile(zipFilePath);
if(zipFile.exists())
{
//檢測文件是否允許刪除,如果不允許刪除,將會拋出SecurityException
=newSecurityManager();
securityManager.checkDelete(zipFilePath);
//刪除已存在的目標文件
zipFile.delete();
}
cos=newCheckedOutputStream(newFileOutputStream(zipFile),newCRC32());
zos=newZipOutputStream(cos);
//如果只是壓縮一個文件,則需要截取該文件的父目錄
StringsrcRootDir=srcPath;
if(srcFile.isFile())
{
intindex=srcPath.lastIndexOf(File.separator);
if(index!=-1)
{
srcRootDir=srcPath.substring(0,index);
}
}
//調用遞歸壓縮方法進行目錄或文件壓縮
zip(srcRootDir,srcFile,zos);
zos.flush();
}
catch(Exceptione)
{
throwe;
}
finally
{
try
{
if(zos!=null)
{
zos.close();
}
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}
/**
*解壓縮zip包
*@paramzipFilePathzip文件的全路徑
*@paramunzipFilePath解壓後的文件保存的路徑
*@paramincludeZipFileName解壓後的文件保存的路徑是否包含壓縮文件的文件名。true-包含;false-不包含
*/
@SuppressWarnings("unchecked")
publicstaticvoinzip(StringzipFilePath,StringunzipFilePath,booleanincludeZipFileName)throwsException
{
if(StringUtils.isEmpty(zipFilePath)||StringUtils.isEmpty(unzipFilePath))
{
thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);
}
FilezipFile=newFile(zipFilePath);
//如果解壓後的文件保存路徑包含壓縮文件的文件名,則追加該文件名到解壓路徑
if(includeZipFileName)
{
StringfileName=zipFile.getName();
if(StringUtils.isNotEmpty(fileName))
{
fileName=fileName.substring(0,fileName.lastIndexOf("."));
}
unzipFilePath=unzipFilePath+File.separator+fileName;
}
//創建解壓縮文件保存的路徑
FileunzipFileDir=newFile(unzipFilePath);
if(!unzipFileDir.exists()||!unzipFileDir.isDirectory())
{
unzipFileDir.mkdirs();
}
//開始解壓
ZipEntryentry=null;
StringentryFilePath=null,entryDirPath=null;
FileentryFile=null,entryDir=null;
intindex=0,count=0,bufferSize=1024;
byte[]buffer=newbyte[bufferSize];
BufferedInputStreambis=null;
BufferedOutputStreambos=null;
ZipFilezip=newZipFile(zipFile);
Enumeration<ZipEntry>entries=(Enumeration<ZipEntry>)zip.entries();
//循環對壓縮包里的每一個文件進行解壓
while(entries.hasMoreElements())
{
entry=entries.nextElement();
//構建壓縮包中一個文件解壓後保存的文件全路徑
entryFilePath=unzipFilePath+File.separator+entry.getName();
//構建解壓後保存的文件夾路徑
index=entryFilePath.lastIndexOf(File.separator);
if(index!=-1)
{
entryDirPath=entryFilePath.substring(0,index);
}
else
{
entryDirPath="";
}
entryDir=newFile(entryDirPath);
//如果文件夾路徑不存在,則創建文件夾
if(!entryDir.exists()||!entryDir.isDirectory())
{
entryDir.mkdirs();
}
//創建解壓文件
entryFile=newFile(entryFilePath);
if(entryFile.exists())
{
//檢測文件是否允許刪除,如果不允許刪除,將會拋出SecurityException
=newSecurityManager();
securityManager.checkDelete(entryFilePath);
//刪除已存在的目標文件
entryFile.delete();
}
//寫入文件
bos=newBufferedOutputStream(newFileOutputStream(entryFile));
bis=newBufferedInputStream(zip.getInputStream(entry));
while((count=bis.read(buffer,0,bufferSize))!=-1)
{
bos.write(buffer,0,count);
}
bos.flush();
bos.close();
}
}
publicstaticvoidmain(String[]args)
{
StringzipPath="d:\ziptest\zipPath";
Stringdir="d:\ziptest\rawfiles";
StringzipFileName="test.zip";
try
{
zip(dir,zipPath,zipFileName);
}
catch(Exceptione)
{
e.printStackTrace();
}
StringzipFilePath="D:\ziptest\zipPath\test.zip";
StringunzipFilePath="D:\ziptest\zipPath";
try
{
unzip(zipFilePath,unzipFilePath,true);
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}
J. 如何使用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將待壓縮的文件以流的形式寫進該壓縮包中。具體實現代碼如下:
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipOutputStream;
/**
*將文件夾下面的文件
*打包成zip壓縮文件
*
*@authoradmin
*
*/
publicfinalclassFileToZip{
privateFileToZip(){}
/**
*將存放在sourceFilePath目錄下的源文件,打包成fileName名稱的zip文件,並存放到zipFilePath路徑下
*@paramsourceFilePath:待壓縮的文件路徑
*@paramzipFilePath:壓縮後存放路徑
*@paramfileName:壓縮後文件的名稱
*@return
*/
publicstaticbooleanfileToZip(StringsourceFilePath,StringzipFilePath,StringfileName){
booleanflag=false;
FilesourceFile=newFile(sourceFilePath);
FileInputStreamfis=null;
BufferedInputStreambis=null;
FileOutputStreamfos=null;
ZipOutputStreamzos=null;
if(sourceFile.exists()==false){
System.out.println("待壓縮的文件目錄:"+sourceFilePath+"不存在.");
}else{
try{
FilezipFile=newFile(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=newFileOutputStream(zipFile);
zos=newZipOutputStream(newBufferedOutputStream(fos));
byte[]bufs=newbyte[1024*10];
for(inti=0;i<sourceFiles.length;i++){
//創建ZIP實體,並添加進壓縮包
ZipEntryzipEntry=newZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
//讀取待壓縮的文件並寫進壓縮包里
fis=newFileInputStream(sourceFiles[i]);
bis=newBufferedInputStream(fis,1024*10);
intread=0;
while((read=bis.read(bufs,0,1024*10))!=-1){
zos.write(bufs,0,read);
}
}
flag=true;
}
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
thrownewRuntimeException(e);
}catch(IOExceptione){
e.printStackTrace();
thrownewRuntimeException(e);
}finally{
//關閉流
try{
if(null!=bis)bis.close();
if(null!=zos)zos.close();
}catch(IOExceptione){
e.printStackTrace();
thrownewRuntimeException(e);
}
}
}
returnflag;
}
publicstaticvoidmain(String[]args){
StringsourceFilePath="D:\TestFile";
StringzipFilePath="D:\tmp";
StringfileName="12700153file";
booleanflag=FileToZip.fileToZip(sourceFilePath,zipFilePath,fileName);
if(flag){
System.out.println("文件打包成功!");
}else{
System.out.println("文件打包失敗!");
}
}
}