Code for Java compression
import java.io.*;
import java.util.zip.*;
/** Compresses a file into a GZip archive. **/
public class SimpleGZip
{
public static void main(String[] args)
{
if(args.length<1)
{
System.out.println("Usage: Java SimpleGZip fileName");
System.exit(0);
}
String fileName = args[0];
try{makeGZip(fileName);}
//try{makeZip(fileName);}
catch(Exception e){System.err.println(e);}
}
/** Creates a GZip archive using the file name passed in as a **/
public static void makeGZip(String fileName) throws IOException, FileNotFoundException
{
File file = new File(fileName);
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin);
//if input file is a.txt, then output file is a.txt.gz
FileOutputStream fos = new FileOutputStream(file + ".gz");
GZIPOutputStream gzos = new GZIPOutputStream(fos);
byte[] buf = new byte[1024];
int len;
//Store the length of a line
while((len = in.read(buf)) >= 0)
{
gzos.write(buf, 0, len);
}
in,close();
gzos.close();
}
/** Creates a Zip archive. If the filename passed in is a directory, the directory's contents will be made into a Zip file **/
public static fvoid makeZip(String fileName) throws IOException, FileNotFoundException
{
File file = File(fileName);
zos = new ZipOutputStream(new FileOutputStream(file + ".zip"));
recurseFiles(file);
zos.close();
}
/** Recurses down a directory and its subdirectories to look for files to add to the Zip. If the current file being looked at is not a directory, the method adds it to the Zip file. **/
private static void recurseFiles(File file) throws IOException, FileNotFoundException
{
if(file.isDirectory())
{
String[] fileNames = file.list();
if(fileNames != null)
for(int i=0; i<fileNames.length; i++)
recurseFiles(new File(file, fileNames[i]));
//file, fileNames[i] for full path
}else
{
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = BufferedInputStream(fin);
byte[] buf = new byte[1024];
int len;
ZipEntry zipEntry = new ZipEntry(file.toString());
zos.putNextEntry(zipEntry);
while((len = in.read(buf)) >= 0)
{
gzos.write(buf, 0, len);
}
in,close();
gzos.closeEntry();
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
Applet与Swing]压缩文件 .rar (2个子文件)
Applet与Swing]压缩文件 .txt 2KB
www.pudn.com.txt 218B
共 2 条
- 1
资源评论
Kinonoyomeo
- 粉丝: 72
- 资源: 1万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功