Easiest way to unpack a jar in java

前端 未结 6 1088
遇见更好的自我
遇见更好的自我 2021-01-20 09:30

Basically, I have a jar file that i want to unzip to a specific folder from a junit test.

What is the easiest way to do this? I am willing to use a free third party

6条回答
  •  天涯浪人
    2021-01-20 10:15

    Here's my version in Scala, would be the same in Java, that unpacks into separate files and directories:

    import java.io.{BufferedInputStream, BufferedOutputStream, ByteArrayInputStream}
    import java.io.{File, FileInputStream, FileOutputStream}
    import java.util.jar._
    
    def unpackJar(jar: File, target: File): Seq[File] = {
      val b   = Seq.newBuilder[File]
      val in  = new JarInputStream(new BufferedInputStream(new FileInputStream(jar)))
    
      try while ({
        val entry: JarEntry = in.getNextJarEntry
        (entry != null) && {
          val f = new File(target, entry.getName)
          if (entry.isDirectory) {
            f.mkdirs()
          } else {
            val bs  = new BufferedOutputStream(new FileOutputStream(f))
            try {
              val arr = new Array[Byte](1024)
              while ({
                val sz = in.read(arr, 0, 1024)
                (sz > 0) && { bs.write(arr, 0, sz); true }
              }) ()
            } finally {
              bs.close()
            }
          }
          b += f
          true
        }
      }) () finally {
        in.close()
      }
    
      b.result()
    }
    

提交回复
热议问题