我正试图从压缩文件输入流中获取特定文件的字节。我有Zipped文件的输入流数据,从这里我获得了ZipEntry并将每个ZipEntry的内容写入输出流并返回字节缓冲区。这将返回缓冲区的输出流大小,但不返回每个特定文件的内容。是否有一种方式可以将FileOutputStream转换为字节或直接读取每个ZipEntry的字节?
我需要将ZipEntry内容作为输出返回,而不是写入文件,只需获取每个zip条目的内容即可。
谢谢您的帮助。
我需要将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;
}
}
FileOutputStream
,而是写入ByteArrayOutputStream
。 - Sotirios Delimanolis