小虾求救。大虾帮偶一下吧。将txt文件压缩成.zip
能不能写一个java程序,将.txt文件压缩成.zip文件。用java.util.zip.GZIPOutputStream.小虾先谢谢大虾了
------解决方案--------------------不会java的路过,帮顶
------解决方案--------------------参数是想要打包的txt文件
import java.io.*;
import java.util.zip.*;
class Zip {
public static void main(String args[]) throws
IOException {
byte b[] = new byte[512];
ZipOutputStream zout = new ZipOutputStream(System.out);
for(int i = 0; i < args.length; i ++) {
InputStream in = new FileInputStream(args[i]);
ZipEntry e = new ZipEntry(args[i].replace(File.separatorChar, '/ '));
zout.putNextEntry(e);
int len=0;
while((len=in.read(b)) != -1) {
zout.write(b,0,len);
}
zout.closeEntry();
print(e);
}
zout.close();
}
public static void print(ZipEntry e){
PrintStream err =
System.err;
err.print( "added " + e.getName());
if (e.getMethod() == ZipEntry.DEFLATED) {
long size = e.getSize();
if (size > 0) {
long csize = e.getCompressedSize();
long ratio = ((size-csize)*100) / size;
err.println( " (deflated " + ratio + "%) ");
}
else {
err.println( " (deflated 0%) ");
}
}
else {
err.println( " (stored 0%) ");
}
}
}
------解决方案--------------------给你一个自己写的方法
import java.io.File;
import java.util.Vector;
import org.apache.tools.zip.ZipOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ZipFiles { public ZipFiles() {
}
/**
* 提供Zip文件/目录的方法。
* @param inputFileName 输入文件名/目录
* @param outputFileName 输出文件名
* @param includeSelfEntry 是否包括自身目录(当需要zip的是目录)
*/
public void zip(String inputFileName, String outputFileName, boolean includeSelfEntry) throws
Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
File inputFile = new File(inputFileName);
if (includeSelfEntry || !inputFile.isDirectory()) {
zip(out, inputFile, inputFile.getName());
} else {
zip(out, inputFile, " ");
}
System.out.println( "zip done ");
out.close();
}
/**
* 提供多个指定Zip文件/目录的方法。
* @param inputFileNames 多个输入文件名/目录
* @param outputFileName 输出文件名
*/
public void zipFiles(Vector inputFileNames, String outputFileName) throws
Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
File inputFile = null;
for (int i = 0; i < inputFileNames.size(); i++) {
inputFile = new File((String)inputFileNames.get(i));
zip(out, inputFile, inputFile.getName());
}
System.out.println( "zip done ");
out.close();
}
private void zip(ZipOutputStream out, File file, String base) throws Exception {
if (file.isDirectory()) {
File[] subfiles = file.listFiles();
if (System.getProperty( "os.name ").startsWith( "Windows ")) {