2017-10-09 39 views
1

我正在通過編譯器運行一些代碼,我必須查詢用戶正在使用哪個操作系統來調用相應的二進制文件。代碼工作,並在IntelliJ中調用二進制文件,但是當我用gradle構建一個jar文件時,我在與temp tempBinaryCopy相對應的行上找到了一個找不到文件的異常(二進制文件)。在IntelliJ中找到的文件,但沒有在內置的jar中

fun assemble(file: String) { 

    val currentDirectory = System.getProperty("user.dir") 

    val binary = when { 
     System.getProperty("os.name").startsWith("Linux") -> javaClass.classLoader.getResource("osx_linux").file 
     System.getProperty("os.name").startsWith("Mac") -> javaClass.classLoader.getResource("osx_mac").file 
     else ->javaClass.classLoader.getResource("osx_win.exe").file 
    } 

    val binaryFile = File(binary).name 
    val assemblyFile = File(file).name 

    val tempBinaryCopy = File(binary).copyTo(File(currentDirectory, binaryFile), true) 
    val tempAssemblyCopy = File(file).copyTo(File(currentDirectory, assemblyFile), true) 

    tempAssemblyCopy.deleteOnExit() 
    tempBinaryCopy.deleteOnExit() 

    Files.setPosixFilePermissions(tempBinaryCopy.toPath(), setOf(PosixFilePermission.OWNER_EXECUTE)) 
    val process = Runtime.getRuntime().exec(arrayOf(tempBinaryCopy.absolutePath, tempAssemblyCopy.absolutePath, "-v")) 
    process.inputStream.bufferedReader().readLines().forEach { println(it) } 
} 

例外

Exception in thread "main" kotlin.io.NoSuchFileException: file:/Users/dross/Desktop/OS.jar!/osx_mac: The source file doesn't exist. 
at kotlin.io.FilesKt__UtilsKt.copyTo(Utils.kt:179) 
at kotlin.io.FilesKt__UtilsKt.copyTo$default(Utils.kt:177) 
at com.max.power.os.assembler.ProvidedAssembler.assemble(ProvidedAssembler.kt:22) 

我也試圖在一個問題上替換行刪除!結果是一樣的。

回答

2

javaClass.classLoader.getResource("osx_linux")爲您提供URL的一個實例,URL.file爲您提供URL的文件部分。只要文件沒有打包到JAR中,這可能會起作用,但正如您可以看到文件打包到JAR中時所看到的那樣失敗。您應該使用getResourceAsStream,並將您收到的InputStream複製到您想要的目的地。

相關問題