How to copy file inside jar to outside the jar?

后端 未结 9 944
深忆病人
深忆病人 2020-11-27 03:37

I want to copy a file from a jar. The file that I am copying is going to be copied outside the working directory. I have done some tests and all methods I try end up with 0

9条回答
  •  暖寄归人
    2020-11-27 04:10

    Java 8 (actually FileSystem is there since 1.7) comes with some cool new classes/methods to deal with this. As somebody already mentioned that JAR is basically ZIP file, you could use

    final URI jarFileUril = URI.create("jar:file:" + file.toURI().getPath());
    final FileSystem fs = FileSystems.newFileSystem(jarFileUri, env);
    

    (See Zip File)

    Then you can use one of the convenient methods like:

    fs.getPath("filename");
    

    Then you can use Files class

    try (final Stream sources = Files.walk(from)) {
         sources.forEach(src -> {
             final Path dest = to.resolve(from.relativize(src).toString());
             try {
                if (Files.isDirectory(from)) {
                   if (Files.notExists(to)) {
                       log.trace("Creating directory {}", to);
                       Files.createDirectories(to);
                   }
                } else {
                    log.trace("Extracting file {} to {}", from, to);
                    Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
                }
           } catch (IOException e) {
               throw new RuntimeException("Failed to unzip file.", e);
           }
         });
    }
    

    Note: I tried that to unpack JAR files for testing

提交回复
热议问题