使用nstask从swift应用程序运行jar文件

时间:2015-01-27 14:00:12

标签: java macos swift jar nstask

我正在尝试从我的swift应用程序执行一个jar文件。我使用下面的代码:

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("MyJar", ofType: "jar")!

let task = NSTask()
task.launchPath = "/usr/bin/java"
task.arguments = ["-jar", path, arg]

let pipe = NSPipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)!
print(output)

当我从xcode执行应用程序时,它运行良好但是当我从应用程序图标启动应用程序时,它不起作用,我不知道为什么......

编辑: 所以我把一些NSLog()放到我的代码中:

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("AudioTagger", ofType: "jar")!

NSLog("%@", "jar path : \(path)")

let task = NSTask()
task.launchPath = "/usr/bin/java"
task.arguments = ["-jar", path, xml]

let pipe = NSPipe()
task.standardOutput = pipe
let errorPipe = NSPipe()
task.standardError = errorPipe
task.launch()
task.waitUntilExit()

NSLog("%@", "Task is finished")

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)!

let errorData = pipe.fileHandleForReading.readDataToEndOfFile()
let errorOutput: String = NSString(data: errorData, encoding: NSUTF8StringEncoding)!

NSLog("%@", output)
NSLog("%@", errorOutput)

我把它放到控制台中:

16:41:09 MyApp: jar path : /Users/User/Library/Developer/Xcode/DerivedData/MyApp-fbeddkvghwjpjpgvrkrfzbjxjvse/Build/Products/Release/MyApp.app/Contents/Resources/MyJar.jar
16:41:09 MyApp: Task is finished
16:41:14 Console: Failed to connect (_consoleX) outlet from (NSApplication) to (ConsoleX): missing setter or instance variable

标准错误似乎是空的,所以我仍然没有得到它......

1 个答案:

答案 0 :(得分:0)

检查Bundle Resources中是否有罐子。

因为如果你使用NSBundle,你需要在你的Bundle Resources中使用Jar。

如果你没有在那里,你必须在Build PhasesCopy Bundle Resources下的Xcode目标中添加JAR。