package com.yqcf.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZIP {
/**
*
* 解压缩文件
* @param inFileName:输入需要解压缩的文件的路径和文件名
* @param outFileName:输出解压缩完的文件的路径和文件名
* @return boolean
*/
public boolean uncoilGZIP(String inFileName, String outFileName) {
// ***************判断参数的是否合理*******************//
if (inFileName == null || "".equals(inFileName) || outFileName == null
|| "".equals(outFileName)) {
System.out.println("解压缩文件失败:文件名为空");
return false;
}
File inFile = new File(inFileName);
File outFile = new File(outFileName);
if (!inFile.exists()) {
System.out.println("解压缩文件失败:待解压缩文件名或路径不存在");
return false;
}
GZIPInputStream input = null;
OutputStream output = null;
try {
if (!outFile.exists()) {
if (!outFile.createNewFile()) {
System.out.println("解压缩文件失败:解压缩后的文件的路径不存在");
return false;
}
}
// 建立gzip压缩文件输入流
input = new GZIPInputStream(new FileInputStream(inFile));
// 建立解压文件输出流
output = new FileOutputStream(outFile);
// 设定读入缓冲区尺寸
byte[] block = new byte[1024];
int len = 0;
while ((len = input.read(block)) != -1) {
output.write(block, 0, len);
}
output.flush();
return true;
} catch (IOException e) {
System.out.println("解压缩文件失败:" + e.getMessage());
return false;
} finally {
// !!!关闭流,保证输入输出完整和释放系统资源.
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
/**
*
* 压缩文件
* @param inFileName:输入要压缩的文件的路径和文件名
* @param outFileName:输出已压缩完的文件的路径和文件名
* @return boolean
*/
public boolean compressGZIP(String inFileName, String outFileName) {
// ***************判断参数的是否合理*******************//
if (inFileName == null || "".equals(inFileName) || outFileName == null
|| "".equals(outFileName)) {
System.out.println("压缩文件失败:文件名为空");
return false;
}
File inFile = new File(inFileName);
File outFile = new File(outFileName);
if (!inFile.exists()) {
System.out.println("压缩文件失败:待压缩文件名或路径不存在");
return false;
}
GZIPOutputStream output = null;
InputStream input = null;
try {
if (!outFile.exists()) {
if (!outFile.createNewFile()) {
System.out.println("压缩文件失败:压缩后文件的路径不存在");
return false;
}
}
// 打开需压缩文件作为文件输入流
input = new FileInputStream(inFile);
// 建立gzip压缩输出流
output = new GZIPOutputStream(new FileOutputStream(outFile));
// 设定读入缓冲区尺寸
byte[] block = new byte[1024];
int len = 0;
while ((len = input.read(block)) != -1) {
output.write(block, 0, len);
}
output.flush();
return true;
} catch (IOException e) {
System.out.println("压缩文件失败:" + e.getMessage());
return false;
} finally {
// !!!关闭流,保证输入输出完整和释放系统资源.
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}