導航:首頁 > 文件教程 > zipfilejava壓縮文件

zipfilejava壓縮文件

發布時間:2024-04-17 00:46:47

Ⅰ 如何使用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("文件打包失敗!");
}
}

}

Ⅱ 如何用java讀取zip文件名和zip內文件的文件名,在線等

public static void te(File f) throws IOException {
if (!.exists() || !f.isDirectory()) {
return;
}
File[] subFiles = f.listFiles();
ZipFile zipFile = null;
for (int i = 0, ii = subFiles == null ? 0 : subFiles.length; i < ii; i++) {
if (subFiles[i].isFile()) {
try {
zipFile = new ZipFile(subFiles[i]);
Enumeration entries = zipFile.entries();
System.out.println("壓縮文件:" + subFiles[i].getAbsolutePath());
while(entries.hasMoreElements())
{
System.out.println(" entry:" + ((ZipEntry)entries.nextElement()).getName());
}
zipFile.close();
} catch (ZipException e) {
//System.out.println(e.getMessage());
}
}
}
}

Ⅲ java壓縮文件的問題

有三種方式實現java壓縮:

1、jdk自帶的包java.util.zip.ZipOutputStream,不足之處,文件(夾)名稱帶中文時,出現亂碼問題,實現代碼如下:
/**
* 功能:把 sourceDir 目錄下的所有文件進行 zip 格式的壓縮,保存為指定 zip 文件
* @param sourceDir 如果是目錄,eg:D:\\MyEclipse\\first\\testFile,則壓縮目錄下所有文件;
* 如果是文件,eg:D:\\MyEclipse\\first\\testFile\\aa.zip,則只壓縮本文件
* @param zipFile 最後壓縮的文件路徑和名稱,eg:D:\\MyEclipse\\first\\testFile\\aa.zip
*/
public File doZip(String sourceDir, String zipFilePath) throws IOException {
File file = new File(sourceDir);
File zipFile = new File(zipFilePath);
ZipOutputStream zos = null;
try {
// 創建寫出流操作
OutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
zos = new ZipOutputStream(bos);

String basePath = null;

// 獲取目錄
if(file.isDirectory()) {
basePath = file.getPath();
}else {
basePath = file.getParent();
}

zipFile(file, basePath, zos);
}finally {
if(zos != null) {
zos.closeEntry();
zos.close();
}
}

return zipFile;
}
/**
* @param source 源文件
* @param basePath
* @param zos
*/
private void zipFile(File source, String basePath, ZipOutputStream zos)
throws IOException {
File[] files = null;
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}

InputStream is = null;
String pathName;
byte[] buf = new byte[1024];
int length = 0;
try{
for(File file : files) {
if(file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) + "/";
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
}else {
pathName = file.getPath().substring(basePath.length() + 1);
is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) > 0) {
zos.write(buf, 0, length);
}
}
}
}finally {
if(is != null) {
is.close();
}
}
}

2、使用org.apache.tools.zip.ZipOutputStream,代碼如下,
package net.szh.zip;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipCompressor {
static final int BUFFER = 8192;

private File zipFile;

public ZipCompressor(String pathName) {
zipFile = new File(pathName);
}

public void compress(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists())
throw new RuntimeException(srcPathName + "不存在!");
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
String basedir = "";
compress(file, out, basedir);
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private void compress(File file, ZipOutputStream out, String basedir) {
/* 判斷是目錄還是文件 */
if (file.isDirectory()) {
System.out.println("壓縮:" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
System.out.println("壓縮:" + basedir + file.getName());
this.compressFile(file, out, basedir);
}
}

/** 壓縮一個目錄 */
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;

File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 遞歸 */
compress(files[i], out, basedir + dir.getName() + "/");
}
}

/** 壓縮一個文件 */
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

3、可以用ant中的org.apache.tools.ant.taskdefs.Zip來實現,更加簡單。
package net.szh.zip;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

public class ZipCompressorByAnt {

private File zipFile;

public ZipCompressorByAnt(String pathName) {
zipFile = new File(pathName);
}

public void compress(String 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();
}
}
測試一下
package net.szh.zip;

public class TestZip {
public static void main(String[] args) {
ZipCompressor zc = new ZipCompressor("E:\\szhzip.zip");
zc.compress("E:\\test");

ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\szhzipant.zip");
zca.compress("E:\\test");
}
}

Ⅳ 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;public class Zip {
// 壓縮
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, null);
System.out.println("zip done");
out.close();
} private static void zip(ZipOutputStream out, File f, String base)
throws Exception {
System.out.println("zipping " + f.getAbsolutePath());
if (f != null && f.isDirectory()) {
File[] fc = f.listFiles();
if (base != null)
out.putNextEntry(new ZipEntry(base + "/"));
base = base == null ? "" : base + "/";
for (int i = 0; i < fc.length; i++) {
zip(out, fc[i], base + fc[i].getName());
}
} else {
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 unzip(String zipFileName, String outputDirectory)
throws Exception {
ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry z;
while ((z = in.getNextEntry()) != null) {
String name = z.getName();
if (z.isDirectory()) {
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
f.mkdir();
System.out.println("MD " + outputDirectory + File.separator
+ name);
} else {
System.out.println("unziping " + z.getName());
File f = new File(outputDirectory + File.separator + name);
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
out.close();
}
}
in.close();
} public void deleteFolder(File dir) {
File filelist[] = dir.listFiles();
int listlen = filelist.length;
for (int i = 0; i < listlen; i++) {
if (filelist[i].isDirectory()) {
deleteFolder(filelist[i]);
} else {
filelist[i].delete();
}
}
dir.delete();// 刪除當前目錄
} public static void main(String[] args) {
try {
// TestZip t = new TestZip();
// t.zip("c:\\test.zip","c:\\test");
// t.unzip("c:\\test.zip","c:\\test2");
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}

Ⅳ Java壓縮與解壓縮問題

/**
*類名:zipFileRelease
*說明:一個zip文件解壓類
*介紹:主要的zip文件釋放方法releaseHandle()
* 用ZipInputStream類和ZipEntry類將zip文件的入口清單列舉出來,然後
* 根據用戶提供的輸出路徑和zip文件的入口進行組合通過DataOutputStream
* 和File類進行文件的創建和目錄的創建,創建文件時的文件數據是通過
* ZipInputStream類、ZipEntry類、InputStream類之間的套嵌組合獲得的。
*注意:如果zip文件中包含中文路徑程序將會拋出異常
*日期:2005-7-1
*作者:Pcera
*/

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("文件讀取異常!");
}
}

Ⅵ java 如何將 txt 文件 變成zip壓縮文件 求例子!!

這個要用 壓縮流類 ZipOutputStream
下面是一個例子 在D盤下有個 名字叫 demo.txt的文件.程序運行後會再D盤下生成一個demo.zip的文件,以下是代碼:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipOutputStreamDemo {
public static void main(String args[]) throws IOException {
//定義要壓縮的文件 也就是說在D盤里有個 demo.txt 的文件(必須要有,否者會有異常,實際應用中可判斷);
File file = new File("d:" + File.separator + "demo.txt");

//定義壓縮文件的名稱
File zipFile = new File("d:" + File.separator + "demo.zip");

//定義輸入文件流
InputStream input = new FileInputStream(file);

//定義壓縮輸出流
ZipOutputStream zipOut = null;

//實例化壓縮輸出流,並制定壓縮文件的輸出路徑 就是D盤下,名字叫 demo.zip
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

zipOut.putNextEntry(new ZipEntry(file.getName()));

//設置注釋
zipOut.setComment("www.demo.com");
int temp = 0;
while((temp = input.read()) != -1) {
zipOut.write(temp);
}
input.close();
zipOut.close();

}
}
希望能幫助樓主,建議樓主多看看JDK文檔,設計到文件的輸出什麼都在JAVA.IO包里,好好看看..
不過樓主要知道,壓縮流也是inputstream和outputstream的子類,但是並沒有定義在java.io包里,而是以一個工具類的形式出現的,但是在用的時候還是需要java.io包的支持的...

Ⅶ 用java小應用程序實現文件壓縮、解壓縮

40.ZIP壓縮文件
/*
import java.io.*;
import java.util.zip.*;
*/
//創建文件輸入流對象
FileInputStream fis=new FileInputStream(%%1);
//創建文件輸出流對象
FileOutputStream fos=new FileOutputStream(%%2);
//創建ZIP數據輸出流對象
ZipOutputStream zipOut=new ZipOutputStream(fos);
//創建指向壓縮原始文件的入口
ZipEntry entry=new ZipEntry(args[0]);
zipOut.putNextEntry(entry);
//向壓縮文件中輸出數據
int nNumber;
byte[] buffer=new byte[1024];
while((nNumber=fis.read(buffer))!=-1)
zipOut.write(buffer,0,nNumber);
//關閉創建的流對象
zipOut.close();
fos.close();
fis.close();
}
catch(IOException e)
{
System.out.println(e);
}

41.獲得應用程序完整路徑
String %%1=System.getProperty("user.dir");

42.ZIP解壓縮
/*
import java.io.*;
import java.util.zip.*;
*/
try{
//創建文件輸入流對象實例
FileInputStream fis=new FileInputStream(%%1);
//創建ZIP壓縮格式輸入流對象實例
ZipInputStream zipin=new ZipInputStream(fis);
//創建文件輸出流對象實例
FileOutputStream fos=new FileOutputStream(%%2);
//獲取Entry對象實例
ZipEntry entry=zipin.getNextEntry();
byte[] buffer=new byte[1024];
int nNumber;
while((nNumber=zipin.read(buffer,0,buffer.length))!=-1)
fos.write(buffer,0,nNumber);
//關閉文件流對象
zipin.close();
fos.close();
fis.close();
}
catch(IOException e) {
System.out.println(e);
}

43.遞歸刪除目錄中的文件
/*
import java.io.*;
import java.util.*;
*/
ArrayList<String> folderList = new ArrayList<String>();
folderList.add(%%1);
for (int j = 0; j < folderList.size(); j++) {
File file = new File(folderList.get(j));
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}

43.ZIP壓縮文件夾
/*
http://findjar.com/index.jsp
import java.io.*;
import org.apache.tools.zip.ZipOutputStream; //這個包在ant.jar里,要到官方網下載
//java.util.zip.ZipOutputStream
import java.util.zip.*;
*/
try {
String zipFileName = %%2; //打包後文件名字
File f=new File(%%1);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
String base= "";
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
}else {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ( (b = in.read()) != -1) {
out.write(b);
}
in.close();
}
out.close();
}catch (Exception ex) {
ex.printStackTrace();
}
/*
切,我剛好寫了個壓縮的,但沒寫解壓的

1. 解壓的(參數兩個,第一個是你要解壓的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;
*/
public class ZipFileList {

public static void main(String[] args) {
extZipFileList(args[0],args[1]);
}

private static void extZipFileList(String zipFileName, String extPlace) {
try {
ZipInputStream in = new ZipInputStream(new FileInputStream(
zipFileName));
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String entryName = entry.getName();
if (entry.isDirectory()) {
File file = new File(extPlace + entryName);
file.mkdirs();
System.out.println("創建文件夾:" + entryName);
} else {
FileOutputStream os = new FileOutputStream(extPlace
+ entryName);
// Transfer bytes from the ZIP file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
in.closeEntry();

}
}
} catch (IOException e) {
}
System.out.println("解壓文件成功");
}
}

壓縮的(參數最少傳兩個,第一個是你壓縮之後的文件存放的位置以及名字,第二個是你要壓縮的文件或者文件夾所在位置,也可以傳多個文件或文件夾)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileOther {

public static String zipFileProcess(ArrayList outputZipFileNameList, String outputZipNameAndPath) {
ArrayList fileNames = new ArrayList();
ArrayList files = new ArrayList();
FileOutputStream fileOut = null;
ZipOutputStream outputStream = null;
FileInputStream fileIn = null;
StringBuffer sb = new StringBuffer(outputZipNameAndPath);
// FileInputStream fileIn =null;
try {
if (outputZipNameAndPath.indexOf(".zip") != -1) {
outputZipNameAndPath = outputZipNameAndPath;
} else {
sb.append(".zip");
outputZipNameAndPath = sb.toString();
}
fileOut = new FileOutputStream(outputZipNameAndPath);
outputStream = new ZipOutputStream(fileOut);
int outputZipFileNameListSize = 0;
if (outputZipFileNameList != null) {
outputZipFileNameListSize = outputZipFileNameList.size();
}
for (int i = 0; i < outputZipFileNameListSize; i++) {
File rootFile = new File(outputZipFileNameList.get(i).toString());
listFile(rootFile, fileNames, files, "");
}
for (int loop = 0; loop < files.size(); loop++) {
fileIn = new FileInputStream((File) files.get(loop));
outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop)));
byte[] buffer = new byte[1024];
while (fileIn.read(buffer) != -1) {
outputStream.write(buffer);
}
outputStream.closeEntry();
fileIn.close();
}
return outputZipNameAndPath;
} catch (IOException ioe) {
return null;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
if (fileIn != null) {
try {
fileIn.close();
} catch (IOException e) {
}
}
}
}

public static void main(String[] args) {
ArrayList outputZipFileName=new ArrayList();
String savePath="";
int argSize = 0;
if (args != null) {
argSize = args.length;
}

if (argSize > 1) {
if(args[0]!=null)
savePath = args[0];
for(int i=1;i<argSize;i++){
if(args[i]!=null){
outputZipFileName.add(args[i]);
}
}
ZipFileOther instance=new ZipFileOther();
instance.zipFileProcess(outputZipFileName,savePath);
} else {
}

}

private static void listFile(File parentFile, List nameList, List fileList, String directoryName) {
if (parentFile.isDirectory()) {
File[] files = parentFile.listFiles();
for (int loop = 0; loop < files.length; loop++) {
listFile(files[loop], nameList, fileList, directoryName + parentFile.getName() + "/");
}
} else {
fileList.add(parentFile);
nameList.add(directoryName + parentFile.getName());
}
}
}

*/

Ⅷ 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);
}
}
}

閱讀全文

與zipfilejava壓縮文件相關的資料

熱點內容
文檔轉成pdf格式文件 瀏覽:621
離子數據怎麼寫 瀏覽:876
jspapijar官網下載 瀏覽:366
html調用文本文件 瀏覽:921
想學數控編程哪裡好 瀏覽:860
js獲取系統動態時間間隔 瀏覽:165
win10改win7進pe卡住 瀏覽:456
u盤中毒ink文件 瀏覽:718
蘋果換機數據遷移包含哪些數據 瀏覽:234
程式控制可編程直流電源在哪裡 瀏覽:598
容積長寬高的數據從什麼面測量 瀏覽:978
蘋果手游工作室 瀏覽:362
數據型號特別多怎麼合並 瀏覽:600
企業微信電腦版怎麼無法接受文件 瀏覽:968
微信個人相冊怎麼隱藏 瀏覽:368
上傳文件時怎麼獲取文件全路徑 瀏覽:955
linuxjs讀取文件 瀏覽:104
exe後綴的pdf文件 瀏覽:381
win8升級到專業版 瀏覽:487
快圖瀏覽quickpiciphone 瀏覽:847

友情鏈接