我需要在系统中向客户提供zip文件视图,并允许客户下载所选文件。
现在我已经记住了所有的zipentry位置,但有没有java zip工具来解压缩zip文件的指定位置? API就像解压缩(file,long entryStart,long entryLength);
答案 0 :(得分:8)
您可以使用以下代码从zip中提取特定文件: -
public static void main(String[] args) throws Exception{
String fileToBeExtracted="fileName";
String zipPackage="zip_name_with_full_path";
OutputStream out = new FileOutputStream(fileToBeExtracted);
FileInputStream fileInputStream = new FileInputStream(zipPackage);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream );
ZipInputStream zin = new ZipInputStream(bufferedInputStream);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
if (ze.getName().equals(fileToBeExtracted)) {
byte[] buffer = new byte[9000];
int len;
while ((len = zin.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
break;
}
}
zin.close();
}
另请参阅此链接:How to extract a single file from a remote archive file?
答案 1 :(得分:8)
这可以在不使用Java 7的NIO2处理字节数组或输入流的情况下完成:
public void extractFile(Path zipFile, String fileName, Path outputFile) throws IOException {
// Wrap the file system in a try-with-resources statement
// to auto-close it when finished and prevent a memory leak
try (FileSystem fileSystem = FileSystems.newFileSystem(zipFile, null)) {
Path fileToExtract = fileSystem.getPath(fileName);
Files.copy(fileToExtract, outputFile);
}
}
答案 2 :(得分:0)
要使用 FileSystems.newFileSystem,您需要使用 URI.create 设置第一个参数
您需要指定正确的协议。 “jar:文件:”
另外:你需要一个带有属性的 Map
map.put("create","true"); (or "false" to extract)
extract("/tmp","photos.zip","tiger.png",map)
void extract(String path, String zip, String entry, Map<String,String> map){
try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jar:file:"+ path + "/" + zip), map)) {
Path fileToExtract = fileSystem.getPath(entry);
Path fileOutZip = Paths.get(path + "/unzipped_" + entry );
Files.copy(fileToExtract, fileOutZip);
}
}