How to extract specific file in a zip file in java

2020-02-12 06:22发布

I need to provide a view of zip file to customer in system, and allow customers download choosed files.

  1. parse the zip file and show on the web page. and remember every zipentry location(for example file1 is starting from byte 100 width length 1024bytes) in backend.
  2. download the specified file when customer click the download button.

now I have rememberred all zipentry locations, but is there java zip tools to unzip the specified location of zip files?? API just like unzip(file, long entryStart, long entryLength);

标签: java zip
3条回答
你好瞎i
2楼-- · 2020-02-12 06:31

You can use the below code to extract a particular file from 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();

    }

Also refer this link: How to extract a single file from a remote archive file?

查看更多
女痞
3楼-- · 2020-02-12 06:31

You can try like this:

ZipFile zf = new ZipFile(file);
try {
  InputStream in = zf.getInputStream(zf.getEntry("file.txt"));
  // ... read from 'in' as normal
} finally {
  zf.close();
}

I havent tried it but in Java 7 ZipFileSystem you can try like this to extract file.TXT file from the zip file.

Path zipfile = Paths.get("/samples/ziptest.zip");
FileSystem fs = FileSystems.newFileSystem(zipfile, env, null);
final Path root = fs.getPath("/file.TXT");
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-12 06:53

This can be done without messing with byte arrays or input streams using Java 7's 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);
    }
}
查看更多
登录 后发表回答