import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class FileCompress
{
// 压缩
public static void gz(String fromFilePath, String toFilePath) throws IOException
{
//读取文件
InputStream fileIn = new FileInputStream(fromFilePath);
byte[] b = new byte[fileIn.available()];
fileIn.read(b);
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
//将文件内容压缩写入ByteArrayOutputStream
gzip.write(b);
gzip.close();
//将压缩内容写入新文件
byte[] ob = out.toByteArray();
OutputStream fileOut = new FileOutputStream(toFilePath);
fileOut.write(ob);
fileOut.flush();
fileOut.close();
}
// 解压缩
public static void ungz(String fromFilePath, String toFilePath) throws IOException
{
//读取文件
InputStream fileIn = new FileInputStream(fromFilePath);
byte[] b = new byte[fileIn.available()];
fileIn.read(b);
//准备写入解压文件中
OutputStream fileOut = new FileOutputStream(toFilePath);
//将读取文件解压
ByteArrayInputStream in = new ByteArrayInputStream(b);
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
//将压缩内容写入新文件
int n;
while ((n = gunzip.read(buffer)) >= 0)
{
fileOut.write(buffer, 0, n);
}
in.close();
gunzip.close();
fileOut.flush();
fileOut.close();
}
public static void main(String[] args) throws IOException
{
String fromFile = "c:/1.xml";
String toFile = "c:/1.gz";
gz(fromFile, toFile);
//ungz(toFile, fromFile);
}
}
|