TNN*_*TNN 5 java zipfile truezip
我有byte [] zipFileAsByteArray
This zip file has rootDir --|
| --- Folder1 - first.txt
| --- Folder2 - second.txt
| --- PictureFolder - image.png
Run Code Online (Sandbox Code Playgroud)
我需要获取两个txt文件并读取它们,而无需在磁盘上保存任何文件。只需在内存中进行即可。
我尝试过这样的事情:
ByteArrayInputStream bis = new ByteArrayInputStream(processZip);
ZipInputStream zis = new ZipInputStream(bis);
Run Code Online (Sandbox Code Playgroud)
另外,我将需要有单独的方法来获取图片。像这样:
public byte[]image getImage(byte[] zipContent);
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我提供想法或好的榜样吗?
这是一个例子:
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;
}
Run Code Online (Sandbox Code Playgroud)
请记住,尽管我正在检查字符串以区分可能的类型,但这容易出错。没有什么可以阻止我发送具有预期扩展名的另一种文件。