「java读取gzip」java读取gz文件

博主:adminadmin 2023-03-22 15:31:08 546

本篇文章给大家谈谈java读取gzip,以及java读取gz文件对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java后台怎么接收一个gzip压缩流,并且解析接受参数

原则上,不需要在代码中处理zip只接收就可以。解析可以按HTTP协议自己解析,也可以使用WEB容器完成

在java中,gzip 压缩和解压多个文件?

直接编译运行!!!

不知道你是要查看压缩文件还是要解压文件,所以发上来两个。

第一个可以查看各个压缩项目;

第二个可以解压文件。

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.*;

import java.util.zip.*;

import javax.swing.*;

import javax.swing.filechooser.FileFilter;

class ZipTest {

public static void main(String[] args) {

ZipTestFrame frame = new ZipTestFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

class ZipTestFrame extends JFrame {

private JComboBox fileCombo;

private JTextArea fileText;

private String zipname;

public ZipTestFrame() {

setTitle("ZipTest");

setSize(400,300);

JMenuBar menuBar = new JMenuBar();

JMenu menu = new JMenu("File");

JMenuItem openItem = new JMenuItem("Open");

menu.add(openItem);

openItem.addActionListener(new OpenAction());

JMenuItem exitItem = new JMenuItem("Exit");

menu.add(exitItem);

exitItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

System.exit(0);

}

});

menuBar.add(menu);

setJMenuBar(menuBar);

fileText = new JTextArea();

fileCombo = new JComboBox();

fileCombo.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

loadZipFile((String)fileCombo.getSelectedItem());

}

});

add(fileCombo, BorderLayout.SOUTH);

add(new JScrollPane(fileText), BorderLayout.CENTER);

}

public class OpenAction implements ActionListener {

public void actionPerformed(ActionEvent event) {

JFileChooser chooser = new JFileChooser();

chooser.setCurrentDirectory(new File("."));

ExtensionFileFilter filter = new ExtensionFileFilter();

filter.addExtension(".zip");

filter.addExtension(".jar");

filter.setDescription("ZIP archives");

chooser.setFileFilter(filter);

int r = chooser.showOpenDialog(ZipTestFrame.this);

if(r == JFileChooser.APPROVE_OPTION) {

zipname = chooser.getSelectedFile().getPath();

scanZipFile();

}

}

}

public void scanZipFile() {

fileCombo.removeAllItems();

try {

ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));

ZipEntry entry;

while((entry = zin.getNextEntry()) != null) {

fileCombo.addItem(entry.getName());

zin.closeEntry();

}

zin.close();

} catch(IOException e) {

e.printStackTrace();

}

}

public void loadZipFile(String name) {

try {

ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));

ZipEntry entry;

fileText.setText("");

while((entry = zin.getNextEntry()) != null) {

if(entry.getName().equals(name)) {

BufferedReader in = new BufferedReader(new InputStreamReader(zin));

String line;

while((line = in.readLine())!=null) {

fileText.append(line);

fileText.append("\n");

}

}

zin.closeEntry();

}

zin.close();

} catch(IOException e) {

e.printStackTrace();

}

}

}

class ExtensionFileFilter extends FileFilter {

private String description = "";

private ArrayListStringextensions = new ArrayListString();

public void addExtension(String extension) {

if(!extension.startsWith("."))

extension = "." + extension;

extensions.add(extension.toLowerCase());

}

public void setDescription(String aDescription) {

description = aDescription;

}

public String getDescription() {

return description;

}

public boolean accept(File f) {

if(f.isDirectory()) return true;

String name = f.getName().toLowerCase();

for(String e : extensions)

if(name.endsWith(e))

return true;

return false;

}

}

///////////////////////////////////////////////////////////

/**

*类名:zipFileRelease

*说明:一个zip文件解压类

*介绍:主要的zip文件释放方法releaseHandle()

* 用ZipInputStream类和ZipEntry类将zip文件的入口清单列举出来,然后

* 根据用户提供的输出路径和zip文件的入口进行组合通过DataOutputStream

* 和File类进行文件的创建和目录的创建,创建文件时的文件数据是通过

* ZipInputStream类、ZipEntry类、InputStream类之间的套嵌组合获得的。

*注意:如果zip文件中包含中文路径程序将会抛出异常

*/

import java.io.*;

import java.util.*;

import java.util.zip.*;

class zipFileRelease{

private String inFilePath;

private String releaseFilePath;

private String[] FileNameArray; //存放文件名称的数组

private ZipEntry entry;

//

private FileInputStream fileDataIn;

private FileOutputStream fileDataOut;

private ZipInputStream zipInFile;

private DataOutputStream writeData;

private DataInputStream readData;

//

private int zipFileCount = 0; //zip文件中的文件总数

private int zipPathCount = 0; //zip文件中的路径总数

/**

*初始化函数

*初始化zip文件流、输出文件流以及其他变量的初始化

*/

public zipFileRelease(String inpath,String releasepath){

inFilePath = inpath;

releaseFilePath = releasepath;

}

/**

*初始化读取文件流函数

*参数:FileInputStream类

*返回值:初始化成功返回0,否则返回-1

*/

protected long initInStream(ZipInputStream zipFileA){

try{

readData = new DataInputStream(zipFileA);

return 0;

}catch(Exception e){

e.printStackTrace();

return -1;

}

}

/**

*测试文件路径

*参数:zip文件的路径和要释放的位置

*返回值:是两位整数,两位数中的十位代表输入路径和输出路径(1输入、2输出)

* 各位数是代表绝对路径还是相对路径(1绝对、0相对)

* 返回-1表示路径无效

protected long checkPath(String inPath,String outPath){

File infile = new File(inPath);

File infile = new File(outPath);

}

*/

/**

*初始化输出文件流

*参数:File类

*返回值:初始化成功返回0,否则返回-1

*/

protected long initOutStream(String outFileA){

try{

fileDataOut = new FileOutputStream(outFileA);

writeData = new DataOutputStream(fileDataOut);

return 0;

}catch(IOException e){

e.printStackTrace();

return -1;

}

}

/**

*测试文件是否存在方法

*参数:File类

*返回值:如果文件存在返回文件大小,否则返回-1

*/

public long checkFile(File inFileA){

if (inFileA.exists()){

return 0;

}else{

return -1;

}

}

/**

*判断文件是否可以读取方法

*参数:File类

*返回值:如果可以读取返回0,否则返回-1

*/

public long checkOpen(File inFileA){

if(inFileA.canRead()){

return inFileA.length();

}else{

return -1;

}

}

/**

*获得zip文件中的文件夹和文件总数

*参数:File类

*返回值:如果正常获得则返回总数,否则返回-1

*/

public long getFilFoldCount(String infileA){

try{

int fileCount = 0;

zipInFile = new ZipInputStream(new FileInputStream(infileA));

while ((entry = zipInFile.getNextEntry()) != null){

if (entry.isDirectory()){

zipPathCount++;

}else{

zipFileCount++;

}

fileCount++;

}

return fileCount;

}catch(IOException e){

e.printStackTrace();

return -1;

}

}

/**

*读取zip文件清单函数

*参数:File类

*返回值:文件清单数组

*/

public String[] getFileList(String infileA){

try{

ZipInputStream AzipInFile = new ZipInputStream(new FileInputStream(infileA));

//创建数组对象

FileNameArray = new String[(int)getFilFoldCount(infileA)];

//将文件名清单传入数组

int i = 0;

while ((entry = AzipInFile.getNextEntry()) != null){

FileNameArray[i++] = entry.getName();

}

return FileNameArray;

}catch(IOException e){

e.printStackTrace();

return null;

}

}

/**

*创建文件函数

*参数:File类

*返回值:如果创建成功返回0,否则返回-1

*/

public long writeFile(String outFileA,byte[] dataByte){

try{

if (initOutStream(outFileA) == 0){

writeData.write(dataByte);

fileDataOut.close();

return 0;

}else{

fileDataOut.close();

return -1;

}

}catch(IOException e){

e.printStackTrace();

return -1;

}

}

/**

*读取文件内容函数

*参数:File类

*返回值:如果读取成功则返回读取数据的字节数组,如果失败则返回空值

*/

protected byte[] readFile(ZipEntry entryA,ZipInputStream zipFileA){

try{

long entryFilelen;

if (initInStream(zipFileA) == 0){

if ((entryFilelen = entryA.getSize()) = 0){

byte[] entryFileData = new byte[(int)entryFilelen];

readData.readFully(entryFileData,0,(int)entryFilelen);

return entryFileData;

}else{

return null;

}

}else{

return null;

}

}catch(IOException e){

e.printStackTrace();

return null;

}

}

/**

*创建目录函数

*参数:要创建目录的路径

*返回值:如果创建成功则返回0,否则返回-1

*/

public long createFolder(String dir){

File file = new File(dir);

if (file.mkdirs()) {

return 0;

}else{

return -1;

}

}

/**

*删除文件

*参数:要删除的文件

*返回值:如果删除成功则返回0,要删除的文件不存在返回-2

* 如果要删除的是个路径则返回-3,删除失败则返回-1

*/

public long deleteFile(String Apath) throws SecurityException {

File file = new File(Apath.trim());

//文件或路径不存在

if (!file.exists()){

return -2;

}

//要删除的是个路径

if (!file.isFile()){

return -3;

}

//删除

if (file.delete()){

return 0;

}else{

return -1;

}

}

/**

*删除目录

*参数:要删除的目录

*返回值:如果删除成功则返回0,删除失败则返回-1

*/

public long deleteFolder(String Apath){

File file = new File(Apath);

//删除

if (file.delete()){

return 0;

}else{

return -1;

}

}

/**

*判断所要解压的路径是否存在同名文件

*参数:解压路径

*返回值:如果存在同名文件返回-1,否则返回0

*/

public long checkPathExists(String AreleasePath){

File file = new File(AreleasePath);

if (!file.exists()){

return 0;

}else{

return -1;

}

}

/**

*删除zip中的文件

*参数:文件清单数组,释放路径

*返回值:如果删除成功返回0,否则返回-1

*/

protected long deleteReleaseZipFile(String[] listFilePath,String releasePath){

long arrayLen,flagReturn;

int k = 0;

String tempPath;

//存放zip文件清单的路径

String[] pathArray = new String[zipPathCount];

//删除文件

arrayLen = listFilePath.length;

for(int i=0;i(int)arrayLen;i++){

tempPath = releasePath.replace('\\','/') + listFilePath[i];

flagReturn = deleteFile(tempPath);

if (flagReturn == -2){

//什么都不作

}else if (flagReturn == -3){

pathArray[k++] = tempPath;

}else if (flagReturn == -1){

return -1;

}

}

//删除路径

for(k = k - 1;k=0;k--){

flagReturn = deleteFolder(pathArray[k]);

if (flagReturn == -1) return -1;

}

return 0;

}

/**

*获得zip文件的最上层的文件夹名称

*参数:zip文件路径

*返回值:文件夹名称,如果失败则返回null

*/

public String getZipRoot(String infileA){

String rootName;

try{

FileInputStream tempfile = new FileInputStream(infileA);

ZipInputStream AzipInFile = new ZipInputStream(tempfile);

ZipEntry Aentry;

Aentry = AzipInFile.getNextEntry();

rootName = Aentry.getName();

tempfile.close();

AzipInFile.close();

return rootName;

}catch(IOException e){

e.printStackTrace();

return null;

}

}

/**

*释放流,释放占用资源

*/

protected void closeStream() throws Exception{

fileDataIn.close();

fileDataOut.close();

zipInFile.close();

writeData.flush();

}

/**

*解压函数

*对用户的zip文件路径和解压路径进行判断,是否存在和打开

*在输入解压路径时如果输入"/"则在和zip文件存放的统计目录下进行解压

*返回值:0表示释放成功

* -1 表示您所要解压的文件不存在、

* -2表示您所要解压的文件不能被打开、

* -3您所要释放的路径不存在、

* -4您所创建文件目录失败、

* -5写入文件失败、

* -6表示所要释放的文件已经存在、

* -50表示文件读取异常

*/

public long releaseHandle() throws Exception{

File inFile = new File(inFilePath);

File outFile = new File(releaseFilePath);

String tempFile;

String zipPath;

String zipRootPath;

String tempPathParent; //存放释放路径

byte[] zipEntryFileData;

//作有效性判断

if (checkFile(inFile) == -1) {

return -1;}

if (checkOpen(inFile) == -1) {

return -2;}

//不是解压再当前目录下时对路径作有效性检验

if (!releaseFilePath.equals("/")){

//解压在用户指定目录下

if (checkFile(outFile) == -1) {

return -3;}

}

//获得标准释放路径

if (!releaseFilePath.equals("/")) {

tempPathParent = releaseFilePath.replace('\\','/')+ "/";

}else{

tempPathParent = inFile.getParent().replace('\\','/')+ "/";

}

//获得zip文件中的入口清单

FileNameArray = getFileList(inFilePath);

//获得zip文件的最上层目录

zipRootPath = getZipRoot(inFilePath);

//

fileDataIn = new FileInputStream(inFilePath);

zipInFile = new ZipInputStream(fileDataIn);

//判断是否已经存在要释放的文件夹

if (zipRootPath.lastIndexOf("/") 0 ){

if (checkPathExists(tempPathParent +

zipRootPath.substring(0,zipRootPath.lastIndexOf("/"))) == -1){

return -6;

}

}else{

if (checkPathExists(tempPathParent + zipRootPath) == -1){

return -6;

}

}

//

try{

//创建文件夹和文件

int i = 0;

while ((entry = zipInFile.getNextEntry()) != null){

if (entry.isDirectory()){

//创建目录

zipPath = tempPathParent + FileNameArray[i];

zipPath = zipPath.substring(0,zipPath.lastIndexOf("/"));

if (createFolder(zipPath) == -1){

closeStream();

deleteReleaseZipFile(FileNameArray,tempPathParent);

return -4;

}

}else{

//读取文件数据

zipEntryFileData = readFile(entry,zipInFile);

//向文件写数据

tempFile = tempPathParent + FileNameArray[i];

//写入文件

if (writeFile(tempFile,zipEntryFileData) == -1){

closeStream();

deleteReleaseZipFile(FileNameArray,tempPathParent);

return -5;

}

}

i++;

}

//释放资源

closeStream();

return 0;

}catch(Exception e){

closeStream();

deleteReleaseZipFile(FileNameArray,tempPathParent);

e.printStackTrace();

return -50;

}

}

/**

*演示函数

*根据用户输入的路径对文件进行解压

*/

public static void main(String args[]) throws Exception {

long flag; //返回标志

String inPath,releasePath;

//获得用户输入信息

BufferedReader userInput = new BufferedReader(

new InputStreamReader(System.in));

System.out.println("请输入zip文件路径:");

inPath = userInput.readLine();

System.out.println("请输入保存路径:");

releasePath = userInput.readLine();

userInput.close();

//执行解压缩

zipFileRelease pceraZip = new zipFileRelease(inPath,releasePath);

flag = pceraZip.releaseHandle();

//出错信息打印

if (flag == 0) System.out.println("释放成功!!!");

if (flag == -1) System.out.println("您所要解压的文件不存在!");

if (flag == -2) System.out.println("您所要解压的文件不能被打开!");

if (flag == -3) System.out.println("您所要释放的路径不存在!");

if (flag == -4) System.out.println("您所创建文件目录失败!");

if (flag == -5) System.out.println("写入文件失败!");

if (flag == -6) System.out.println("文件已经存在!");

if (flag == -50) System.out.println("文件读取异常!");

}

}

java怎么读取Zip和RAR里面的文件啊?

java.util.zip.*这个包下有ZipInputStream和ZipOutputStream这两个类,用于ZIP的读入解压,和生成ZIP文件的打包。

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.Enumeration;

import java.util.List;

import java.util.zip.ZipEntry;

import java.util.zip.ZipFile;

import java.util.zip.ZipOutputStream;

import java.util.zip.GZIPInputStream;

import java.io.DataInputStream;

/**

* Description: 此类用于...

*

* @author wunaigang(2005-6-21)

* @version 1.0.0

*/

public class ZipManager {

/**

* zip压缩功能测试. 将d:\\temp\\zipout目录下的所有文件连同子目录压缩到d:\\temp\\out.zip.

*

* @param baseDir 所要压缩的目录名(包含绝对路径)

* @param objFileName 压缩后的文件名

* @throws Exception

*/

public void createZip(String baseDir, String objFileName) throws Exception {

File folderObject = new File(baseDir);

if (folderObject.exists()){

List fileList = getSubFiles(new File(baseDir));

//压缩文件名

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName));

ZipEntry ze = null;

byte[] buf = new byte[1024];

int readLen = 0;

for (int i = 0; i fileList.size(); i++) {

File f = (File) fileList.get(i);

System.out.println("Adding: " + f.getPath() + f.getName());

//创建一个ZipEntry,并设置Name和其它的一些属性

ze = new ZipEntry(getAbsFileName(baseDir, f));

ze.setSize(f.length());

ze.setTime(f.lastModified());

//将ZipEntry加到zos中,再写入实际的文件内容

zos.putNextEntry(ze);

InputStream is = new BufferedInputStream(new FileInputStream(f));

while ((readLen = is.read(buf, 0, 1024)) != -1) {

zos.write(buf, 0, readLen);

}

is.close();

System.out.println("done...");

}

zos.close();

}else{

throw new Exception("this folder isnot exist!");

}

}

/**

* zip压缩功能测试. 将指定文件压缩后存到一压缩文件中

*

* @param baseDir 所要压缩的文件名

* @param objFileName 压缩后的文件名

* @return 压缩后文件的大小

* @throws Exception

*/

public long createFileToZip(String zipFilename,String sourceFileName) throws Exception {

File sourceFile = new File(sourceFileName);

byte[] buf = new byte[1024];

//压缩文件名

File objFile = new File(zipFilename);

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFile));

ZipEntry ze = null;

//创建一个ZipEntry,并设置Name和其它的一些属性

ze = new ZipEntry(sourceFile.getName());

ze.setSize(sourceFile.length());

ze.setTime(sourceFile.lastModified());

//将ZipEntry加到zos中,再写入实际的文件内容

zos.putNextEntry(ze);

InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));

int readLen = -1;

while ((readLen = is.read(buf, 0, 1024)) != -1) {

zos.write(buf, 0, readLen);

}

is.close();

zos.close();

return objFile.length();

}

/**

* zip压缩功能测试. 将指定文件压缩后存到一压缩文件中

*

* @param baseDir 所要压缩的文件名

* @param objFileName 压缩后的文件名

* @return 压缩后文件的大小

* @throws Exception

*/

public long createFileToZip(File sourceFile,File zipFile)throws IOException {

byte[] buf = new byte[1024];

//压缩文件名

File objFile = zipFile;

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFile));

ZipEntry ze = null;

//创建一个ZipEntry,并设置Name和其它的一些属性

ze = new ZipEntry(sourceFile.getName());

ze.setSize(sourceFile.length());

ze.setTime(sourceFile.lastModified());

//将ZipEntry加到zos中,再写入实际的文件内容

zos.putNextEntry(ze);

InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));

int readLen = -1;

while ((readLen = is.read(buf, 0, 1024)) != -1) {

zos.write(buf, 0, readLen);

}

is.close();

zos.close();

return objFile.length();

}

/**

* 测试解压缩功能. 将d:\\download\\test.zip连同子目录解压到d:\\temp\\zipout目录下.

*

* @throws Exception

*/

public void releaseZipToFile(String sourceZip, String outFileName)

throws IOException{

ZipFile zfile=new ZipFile(sourceZip);

System.out.println(zfile.getName());

Enumeration zList=zfile.entries();

ZipEntry ze=null;

byte[] buf=new byte[1024];

while(zList.hasMoreElements()){

//从ZipFile中得到一个ZipEntry

ze=(ZipEntry)zList.nextElement();

if(ze.isDirectory()){

continue;

}

//以ZipEntry为参数得到一个InputStream,并写到OutputStream中

OutputStream os=new BufferedOutputStream(new FileOutputStream(getRealFileName(outFileName, ze.getName())));

InputStream is=new BufferedInputStream(zfile.getInputStream(ze));

int readLen=0;

while ((readLen=is.read(buf, 0, 1024))!=-1) {

os.write(buf, 0, readLen);

}

is.close();

os.close();

System.out.println("Extracted: "+ze.getName());

}

zfile.close();

}

/**

* 取得指定目录下的所有文件列表,包括子目录.

*

* @param baseDir

* File 指定的目录

* @return 包含java.io.File的List

*/

private List getSubFiles(File baseDir) {

List ret = new ArrayList();

//File base=new File(baseDir);

File[] tmp = baseDir.listFiles();

for (int i = 0; i tmp.length; i++) {

if (tmp[i].isFile()) {

ret.add(tmp[i]);

}

if (tmp[i].isDirectory()) {

ret.addAll(getSubFiles(tmp[i]));

}

}

return ret;

}

/**

* 给定根目录,返回一个相对路径所对应的实际文件名.

*

* @param baseDir

* 指定根目录

* @param absFileName

* 相对路径名,来自于ZipEntry中的name

* @return java.io.File 实际的文件

*/

private File getRealFileName(String baseDir, String absFileName) {

String[] dirs = absFileName.split("/");

//System.out.println(dirs.length);

File ret = new File(baseDir);

//System.out.println(ret);

if (dirs.length 1) {

for (int i = 0; i dirs.length - 1; i++) {

ret = new File(ret, dirs[i]);

}

}

if (!ret.exists()) {

ret.mkdirs();

}

ret = new File(ret, dirs[dirs.length - 1]);

return ret;

}

/**

* 给定根目录,返回另一个文件名的相对路径,用于zip文件中的路径.

*

* @param baseDir

* java.lang.String 根目录

* @param realFileName

* java.io.File 实际的文件名

* @return 相对文件名

*/

private String getAbsFileName(String baseDir, File realFileName) {

File real = realFileName;

File base = new File(baseDir);

String ret = real.getName();

while (true) {

real = real.getParentFile();

if (real == null)

break;

if (real.equals(base))

break;

else {

ret = real.getName() + "/" + ret;

}

}

System.out.println("TTTTT" + ret);

return ret;

}

public void testReadZip() throws Exception{

String baseDir="d:\\temp\\zipout";

ZipFile zfile=new ZipFile("d:\\download\\src.zip");

System.out.println(zfile.getName());

Enumeration zList=zfile.entries();

ZipEntry ze=null;

byte[] buf=new byte[1024];

while(zList.hasMoreElements()){

//从ZipFile中得到一个ZipEntry

ze=(ZipEntry)zList.nextElement();

if(ze.isDirectory()){

continue;

}

//以ZipEntry为参数得到一个InputStream,并写到OutputStream中

OutputStream os=new BufferedOutputStream(new FileOutputStream(getRealFileName(baseDir, ze.getName())));

InputStream is=new BufferedInputStream(zfile.getInputStream(ze));

int readLen=0;

while ((readLen=is.read(buf, 0, 1024))!=-1) {

os.write(buf, 0, readLen);

}

is.close();

os.close();

System.out.println("Extracted: "+ze.getName());

}

zfile.close();

}

public static void main(String args[]){

ZipManager manager = new ZipManager();

try {

//manager.releaseZipToFile("c:\\test.zip","c:\\test");

manager.testReadZip();

}

catch (Exception e) {}

System.out.println("over");

}

}

java怎么判断一串字符串是否是GZIPOutputStream后的内容

把字符串转换成byte数组 判断该文件的文件头 GZIP文件头是0x1F 0x8B,也就是bytes[0] == 0x1F bytes[1] == 0x8B

关于java读取gzip和java读取gz文件的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。