A. 你好,最近我也遇到用java压缩和解压,向你咨询下你的解决方案什么,你是怎么用文件流方式去压缩
package com.onewaveinc.cwds.commons.utils;
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.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @ fz 2010-7-30
* @Description 把指定文件夹下的所有文件压缩为指定文件夹下指定zip文件;把指定文件夹下的zip文件解压到指定目录下
*/
public class ZipUtils {
private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class);
private static final String SEPARATE = "/";
/**
* @Author fz 2010-7-30
* @param sourceDir 待压缩目录
* @param zipFile 压缩文件名称
* @throws Exception
* @Description 把sourceDir目录下的所有文件进行zip格式的压缩,保存为指定zip文件
*/
public static void zip(String sourceDir, String zipFile) throws Exception {
OutputStream os = null;
// try {
os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
ZipOutputStream zos = new ZipOutputStream(bos);
File file = new File(sourceDir);
String basePath = null;
if (file.isDirectory()) {
basePath = file.getPath();
} else {
// 直接压缩单个文件时,取父目录
basePath = file.getParent();
}
zipFile(file, basePath, zos);
zos.closeEntry();
zos.close();
// } catch (Exception e) {
// logger.error("压缩文件或文件夹" + sourceDir + "时发生异常");
// e.printStackTrace();
// }
}
/**
* @Author fz 2010-7-30
* @param source 源文件
* @param basePath 待压缩文件根目录
* @param zos 文件压缩流
* @Description 执行文件压缩成zip文件
*/
private static void zipFile(File source, String basePath, ZipOutputStream zos) {
File[] files = new File[0];
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}
//存相对路径(相对于待压缩的根目录)
String pathName = null;
byte[] buf = new byte[1024];
int length = 0;
try {
for (File file : files) {
if (file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) + SEPARATE;
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
} else {
pathName = file.getPath().substring(basePath.length() + 1);
InputStream 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);
}
is.close();
}
}
} catch (Exception e) {
logger.error("压缩文件" + source + "时发生异常");
e.printStackTrace();
}
}
/**
* @Author fz 2010-7-30
* @param zipfile 待解压文件
* @param destDir 解压文件存储目录
* @throws Exception
* @Description 解压zip文件,只能解压zip文件
*/
@SuppressWarnings("unchecked")
public static void unZip(String zipfile, String destDir) throws Exception {
destDir = destDir.endsWith(SEPARATE) ? destDir : destDir + SEPARATE;
byte b[] = new byte[1024];
int length;
ZipFile zipFile;
// try {
zipFile = new ZipFile(new File(zipfile));
Enumeration enumeration = zipFile.getEntries();
ZipEntry zipEntry = null;
while (enumeration.hasMoreElements()) {
zipEntry = (ZipEntry) enumeration.nextElement();
File loadFile = new File(destDir + zipEntry.getName());
if (zipEntry.isDirectory()) {
loadFile.mkdirs();
} else {
if (!loadFile.getParentFile().exists()) {
loadFile.getParentFile().mkdirs();
}
OutputStream outputStream = new FileOutputStream(loadFile);
InputStream inputStream = zipFile.getInputStream(zipEntry);
while ((length = inputStream.read(b)) > 0)
outputStream.write(b, 0, length);
outputStream.close();
inputStream.close();
}
}
zipFile.close();
// } catch (IOException e) {
// logger.error("解压文件" + zipfile + "时发生异常");
// e.printStackTrace();
// }
}
}
B. 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);
}
}
}
C. 高分:用java实现服务器上多个文件先打包,然后下载,下载完成后删除包!
可以抄把这些url,name暂存到session里面
下载和袭上传可以使用插件jspsmart
很久没有使用了 稍微看一下API吧jspsmart就是把上传和下载的工作封装简化,所以使用非常简单的
下载完成后调用file.delete();就在服务器上删掉了
D. 如何使用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("文件打包失败!");
}
}
}
E. 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);
代码大致如此,请参考。
F. java怎么下载压缩文件
可以用java的输入,输出流,设置返回的类型为下转
response.setContentType("application/x-download");//设置为下载application/x-download
String filedownload = "/要下载的文件专名";//即将下载的文件的相对路径属
String filedisplay = "最终要显示给用户的保存文件名";//下载文件时显示的文件保存名称
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);
G. 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");
}
}
H. 用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());
}
}
}
*/