在java中读取Zip文件内容而不进行解压缩
我有byte[]zipFileAsByteArray在java中读取Zip文件内容而不进行解压缩,java,zipfile,truezip,Java,Zipfile,Truezip,我有byte[]zipFileAsByteArray This zip file has rootDir --| | --- Folder1 - first.txt | --- Folder2 - second.txt | --- PictureFolder - image.png 我需要的是得到两个txt文件并读取它们
This zip file has rootDir --|
| --- Folder1 - first.txt
| --- Folder2 - second.txt
| --- PictureFolder - image.png
我需要的是得到两个txt文件并读取它们,而不在磁盘上保存任何文件。就在记忆中做吧
我试过这样的方法:
ByteArrayInputStream bis = new ByteArrayInputStream(processZip);
ZipInputStream zis = new ZipInputStream(bis);
public byte[]image getImage(byte[] zipContent);
此外,我需要有单独的方法去得到图片。大概是这样的:
ByteArrayInputStream bis = new ByteArrayInputStream(processZip);
ZipInputStream zis = new ZipInputStream(bis);
public byte[]image getImage(byte[] zipContent);
有人能帮我提供一些想法或好的例子吗?以下是一个例子:
public static void main(String[] args) throws IOException {
ZipFile zip = new ZipFile("C:\\Users\\mofh\\Desktop\\test.zip");
for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (!entry.isDirectory()) {
if (FilenameUtils.getExtension(entry.getName()).equals("png")) {
byte[] image = getImage(zip.getInputStream(entry));
//do your thing
} else if (FilenameUtils.getExtension(entry.getName()).equals("txt")) {
StringBuilder out = getTxtFiles(zip.getInputStream(entry));
//do your thing
}
}
}
}
private static StringBuilder getTxtFiles(InputStream in) {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
try {
while ((line = reader.readLine()) != null) {
out.append(line);
}
} catch (IOException e) {
// do something, probably not a text file
e.printStackTrace();
}
return out;
}
private static byte[] getImage(InputStream in) {
try {
BufferedImage image = ImageIO.read(in); //just checking if the InputStream belongs in fact to an image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
return baos.toByteArray();
} catch (IOException e) {
// do something, it is not a image
e.printStackTrace();
}
return null;
}
请记住,虽然我正在检查字符串以区分可能的类型,但这很容易出错。没有任何东西可以阻止我发送另一种具有预期扩展名的文件。您可以执行以下操作:
public static void main(String args[]) throws Exception
{
//bis, zis as you have
try{
ZipEntry file;
while((file = zis.getNextEntry())!=null) // get next file and continue only if file is not null
{
byte b[] = new byte[(int)file.getSize()]; // create array to read.
zis.read(b); // read bytes in b
if(file.getName().endsWith(".txt")){
// read files. You have data in `b`
}else if(file.getName().endsWith(".png")){
// process image
}
}
}
finally{
zis.close();
}
}
我想你要找的东西可以在:。对于与图像相关的内容,您应该可以通过以下内容来完成:。为了检测是否调用getImage方法,请检查文件的扩展名。我没有ZipFile zip=new ZipFile(“C:\\Users\\mofh\\Desktop\\test.zip”);我的条目是ZipInputStream zis=新的ZipInputStream(bis);那就简单地使用它吧。。。如果您有zip的字节[],只需
ZipFile zip=new ZipInputStream(new ByteArrayInputStream(processZip))
@dambros将更好地使用try with resources for zip文件:try(ZipFile zip=…){
file.getSize()return-1;