A. 誰有把多個文件夾壓縮成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壓縮
B. 電腦文件zip如何壓縮java實現對zip文件的壓縮
電腦文件zip如何壓縮(java實現對zip文件的壓縮)
一、java實現壓縮為zip
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.zip.ZipEntry;
importjava.util.zip.ZipOutputStream;
publicclassZipUtils{
privatestaticfinalintBUFFER_SIZE=2*1024;
publicstaticvoiddirFile(Filedir){
File[]files=dir.listFiles();//得到File數組,獲得目錄下所有文件
for(Filefile:files){//遍歷所有的子目錄和文件
if(file.isDirectory()){
dirFile(file);//如果是目錄遞歸調用dirFile()
}
//成功壓縮文件後,對原文件進行刪除
file.delete();
}
//順帶把對應的目錄進行刪除
dir.delete();
}
/**
*壓縮成ZIP方法1
*@paramsrcDir壓縮文件夾路徑
*@paramout壓縮文件輸出流
*@paramKeepDirstructure是否保留原來的目錄結構,true:保留目錄結構;
*false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
*@throwsRuntimeException壓縮失敗會拋出運行時異常
*/
publicstaticvoidtoZip(StringsrcDir,OutputStreamout,booleanKeepDirstructure)
throwsRuntimeException{
longstart=System.currentTimeMillis();
ZipOutputStreamzos=null;
try{
zos=newZipOutputStream(out);
FilesourceFile=newFile(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirstructure);
longend=System.currentTimeMillis();
System.out.println("壓縮完成,耗時:"+(end-start)+"ms");
}catch(Exceptione){
thrownewRuntimeException("ziperrorfromZipUtils",e);
}finally{
if(zos!=null){
try{
zos.close();
}catch(IOExceptione){
e.printstacktrace();
}
}
}
}
/**
*遞歸壓縮方法
*@paramsourceFile源文件
*@paramzoszip輸出流
*@paramname壓縮後的名稱
*@paramKeepDirstructure是否保留原來的目錄結構,會壓縮失敗)
*@throwsException
*/
privatestaticvoidcompress(FilesourceFile,ZipOutputStreamzos,Stringname,
booleanKeepDirstructure)throwsException{
byte[]buf=newbyte[BUFFER_SIZE];
if(sourceFile.isFile()){
//向zip輸出流中添加一個zip實體,構造器中name為zip實體的文件的名字
zos.putNextEntry(newZipEntry(name));
//文件到zip輸出流中
intlen;
FileInputStreamin=newFileInputStream(sourceFile);
while((len=in.read(buf))!=-1){
zos.write(buf,len);
}
//Completetheentry
zos.closeEntry();
in.close();
}else{
File[]listFiles=sourceFile.listFiles();
if(listFiles==null||listFiles.length==0){
//需要保留原來的文件結構時,需要對空文件夾進行處理
if(KeepDirstructure){
//空文件夾的處理
zos.putNextEntry(newZipEntry(name+"/"));
//沒有文件,不需要文件的
zos.closeEntry();
}
}else{
for(Filefile:listFiles){
//判斷是否需要保留原來的文件結構
if(KeepDirstructure){
//注意:file.getName()前面需要帶上父文件夾的名字加一斜杠,
//不然最後壓縮包中就不能保留原來的文件結構,即:所有文件都跑到壓縮包根目錄下了
compress(file,name+"/"+file.getName(),KeepDirstructure);
}else{
compress(file,file.getName(),KeepDirstructure);
}
}
}
}
}
}
C. 用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());
}
}
}
*/
D. JAVA怎麼把zip文件解壓到指定位置
剛好我在項目中用到了,送給你,希望你能用上。
/**
* 解壓,處理下載的zip工具包文件
*
* @param directory
* 要解壓到的目錄
* @param zip
* 工具包文件
*
* @throws Exception
* 操作失敗時拋出異常
*/
public static void unzipFile(String directory, File zip) throws Exception
{
try
{
ZipInputStream zis = new ZipInputStream(new FileInputStream(zip));
ZipEntry ze = zis.getNextEntry();
File parent = new File(directory);
if (!parent.exists() && !parent.mkdirs())
{
throw new Exception("創建解壓目錄 \"" + parent.getAbsolutePath() + "\" 失敗");
}
while (ze != null)
{
String name = ze.getName();
File child = new File(parent, name);
FileOutputStream output = new FileOutputStream(child);
byte[] buffer = new byte[10240];
int bytesRead = 0;
while ((bytesRead = zis.read(buffer)) > 0)
{
output.write(buffer, 0, bytesRead);
}
output.flush();
output.close();
ze = zis.getNextEntry();
}
zis.close();
}
catch (IOException e)
{
}
}
E. 如何使用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("文件打包失敗!");
}
}
}
F. java中怎麼用cmd命令解壓zip文件
對於zip文件,java有自帶類庫java.util.zip;可是要想解壓rar文件只能靠第三方類庫,我試過兩個:com.github.junrar和de.innosystec.unrar,前者解壓時可能會出現crcError,後者pom配置時報錯;利用cmd命令調用winRAR進行解壓,無疑方便快捷很多。
調用cmd命令
public static boolean exe(String cmd) {
Runtime runtime = Runtime.getRuntime(); try {
Process p = runtime.exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
String line = reader.readLine(); while(line!=null) {
logger.info(line);
line = reader.readLine();
}
reader.close(); if(p.waitFor()!=0) { return false;
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) { // TODO Auto-generated catch block
e.printStackTrace();
} return true;
}
首先利用runtime.exec()執行指令,得到process,從process.getInputStream()中獲取回顯字元並列印,列印回顯時可能會出現中文亂碼,這個和操作系統編碼有關,我這里是GBK編碼,所以在new inputstreamReader時加入了編碼參數」GBK「
命令行字元串
如果需要調用cmd命令,如cd等,可寫」cmd c cd 目錄」。對於直接調用exe執行,則可以寫成」exe文件絕對路徑 參數」,在命令行字元串中,含有空格的路徑或者字元串應該再加上引號,即」」exe文件絕對路徑」 」參數」「
winRAR調用
我這里安裝目錄是C:/Program Files/WinRAR,將D:1.rar 解壓到D:,則寫成」」C:/Program Files/WinRAR/unRar.exe」 x -y D:/1.rar D:/」,x代表絕對路徑解壓,-y表示全部確定;壓縮的命令如下:「」C:/Program Files/WinRAR/rar.exe」 a -ep1 D:2.rar D:源目錄」,a表示添加文件到壓縮文件,-ep1表示排除基本目錄,如D:winrar ar這個目錄,如果沒有-ep1那麼壓縮包中會出現winrar目錄路徑,而加了之後就只將當前目錄打包,只有rar目錄