转载地址:http://blog.csdn.net/caolaosanahnu/article/details/9299865
import java.util.zip.GZIPInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class UncompressFileGZIP {
/**
* Uncompress the incoming file. 解压缩的文件。
* @param inFileName 未压缩文件的名称
*/
private static void doUncompressFile(String inFileName) {
try {
if (!getExtension(inFileName).equalsIgnoreCase("gz")) {
System.err.println("文件名必须有扩展名 \".gz\"");
System.exit(1);
}
System.out.println("打开压缩文件.");
GZIPInputStream in = null;
try {
in = new GZIPInputStream(new FileInputStream(inFileName));
} catch(FileNotFoundException e) {
System.err.println("文件未找到. " + inFileName);
System.exit(1);
}
System.out.println("打开输出文件.");
String outFileName = getFileName(inFileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(outFileName);
} catch (FileNotFoundException e) {
System.err.println("不能写入文件. " + outFileName);
System.exit(1);
}
System.out.println("将字节从压缩文件传输到输出文件.");
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
System.out.println("关闭文件和流");
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Used to extract and return the extension of a given file. 用于提取和返回给定文件的扩展名
* @param f Incoming file to get the extension of 输入文件以获得扩展
* @return <code>String</code> representing the extension of the incoming 表示传入的扩展
* file.
*/
public static String getExtension(String f) {
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1) {
ext = f.substring(i+1);
}
return ext;
}
/**
* Used to extract the filename without its extension. 用于在没有扩展名的情况下提取文件名。
* @param f Incoming file to get the filename 输入文件以获取文件名
* @return <code>String</code> representing the filename without its 在没有它的情况下表示文件名
* extension.
*/
public static String getFileName(String f) {
String fname = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1) {
fname = f.substring(0,i);
}
return fname;
}
/**
* Sole entry point to the class and application. 唯一进入类和应用程序的入口点。
* @param args Array of String arguments. 字符串参数的args数组
*/
public static void main(String[] args) {
doUncompressFile("C:\\Users\\Administrator\\Desktop\\2017091117.gz");
}
}