作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有字节[] zipFileAsByteArray
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);
有人可以帮我提供想法或好的例子吗?
最佳答案
这是一个例子:
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;
}
请记住,虽然我正在检查字符串以区分可能的类型,但这是容易出错的。没有什么能阻止我发送具有预期扩展名的另一种类型的文件。
关于java - 无需在 java 中解压缩即可读取 Zip 文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36548755/
这实际上是我问的问题的一部分here ,该问题没有得到答复,最终被标记为重复。 问题:我只需使用 @Autowired 注释即可使用 JavaMailSender。我没有通过任何配置类公开它。 @Co
我是一名优秀的程序员,十分优秀!