简体   繁体   中英

extract file from zip file using nio filesystem

This is my function to extract a file (path) from an existing zip. The problem is fic is null because the operation is unsupported due to the provider not being the same.(based on the documentation)

I am using jdk 8.

public File method(){
 URI uri = new File(zipFilePath).toURI();//URI.create("jar:file:"+zipFilePath);
        Map<String, String> env = new HashMap<>();
        env.put("create", "true");
        File fic = null;
        FileSystem zipfs = null;
        try {
            zipfs = FileSystems.newFileSystem(URI.create("jar:"+uri),env);

            for(Path path : zipfs.getRootDirectories()){
                System.out.println(path);

                /*Files.walk(path).forEach(p -> {
                           if(p.getFileName()!=null && p.getFileName().toString().contains(fileToExtract)){
                               System.out.println(p.getFileName());
                           }
                        }
                );*/

               Path pathFound = Files.walk(path).filter(p -> p.getFileName()!=null &&  p.getFileName().toString().contains(fileToExtract)).findAny().orElse(null);

                if(pathFound!=null){
                    fic = pathFound.toFile();
                    break;
                }
            }

        }
        catch(Exception e){
            log.error(e.getMessage());
        }finally{
            // close the file system
           FileIOUtil.closeNioFileSystem(zipfs);
        }

        return fic;
}

Look at this link. The technic is to use an outputstream instead of converting to a file.

https://www.journaldev.com/17794/java-files-nio-files-class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM