我试图从压缩文件输入流中获取特定文件的字节.我有Zipped文件的输入流数据.从这里我得到ZipEntry并将每个ZipEntry的内容写入输出流并返回字节缓冲区.这将返回缓冲区大小输出流,但不返回每个特定文件的内容.有没有办法可以将FileOutputStream转换为字节或直接读取每个ZipEntry的字节?
我需要返回ZipEntry内容作为输出.我不想写一个文件,只是获取每个zip条目的内容.
谢谢您的帮助.
public final class ArchiveUtils {
private static String TEMP_DIR = "/tmp/unzip/";
public static byte[] unZipFromByteStream(byte[] data, String fileName) {
ZipEntry entry = null;
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(data));
File tempDirectory = ensureTempDirectoryExists(TEMP_DIR);
try {
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory()) {
System.out.println("-" + entry.getName());
File file = new File(tempDirectory + "/"+ entry.getName());
if (!new File(file.getParent()).exists())
new File(file.getParent()).mkdirs();
OutputStream out = new FileOutputStream(entry.getName());
byte[] byteBuff = new byte[1024];
int bytesRead = 0;
while ((bytesRead = zis.read(byteBuff)) != -1)
{
out.write(byteBuff, 0, bytesRead);
}
out.close();
if(entry.getName().equals(fileName)){
return byteBuff;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static File ensureTempDirectoryExists(String outputPath) {
File outputDirectory = new File(outputPath);
if (!outputDirectory.exists()) {
outputDirectory.mkdir();
}
return outputDirectory;
}
}
解决方法:
像这样使用java.io.ByteArrayOutputStream –
ByteArrayOutputStream out = null; // outside of your loop (for scope).
// where you have a FileOutputStream.
out = new ByteArrayOutputStream(); // doesn't use entry.getName().
然后你就可以了
return (out == null) ? null : out.toByteArray();