简体   繁体   English

如何在Cocoa App中打开jar文件

[英]How to open a jar file in a Cocoa App

I am trying to execute a jar in my Cocoa app. 我试图在我的可可应用程序中执行一个jar。 My research tells me I should use NSTask . 我的研究告诉我,我应该使用NSTask However, I am only able to get system() to work. 但是,我只能使system()工作。 Eg: 例如:

// This works
system("cd /path/to ; /usr/bin/java -jar file.jar");

But this doesn't work: 但这不起作用:

// This does not work
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/java"];
[task setArguments:[NSArray arrayWithObjects: @"-jar", @"/path/to/test.jar", nil] ];
[task launch];

I get a class not found Java exception when I run my app because it cannot find its dependencies. 我在运行应用程序时遇到未找到Java异常的类,因为该类找不到其依赖项。

There is no general error in your code, I tried it out myself. 您的代码中没有一般错误,我自己尝试过。

I assume that you have defined a CLASSPATH environment variable in your .profile , .bashrc or whatever, that is required to execute the Java file. 我假设您已经在.profile.bashrc或任何其他文件中定义了执行Java文件所需的CLASSPATH环境变量。

system() uses the shell to execute your command, and therefore the CLASSPATH is inherited by the java command. system()使用shell执行命令,因此CLASSPATH由java命令继承。

NSTask on the other hand does not use the shell, so java would not know about the CLASSPATH from your profile. 另一方面, NSTask 使用外壳程序,因此java不会从您的配置文件中了解CLASSPATH。

The solution would be to add @"-cp", @"<your class path>" to the arguments. 解决方案是在参数中添加@"-cp", @"<your class path>"

UPDATE UPDATE

As it turned out in the discussion, the problem in this case was not the class path, but the current working directory . 在讨论中发现,这种情况下的问题不是类路径,而是当前的工作目录 Adding 添加

[task setCurrentDirectoryPath:@"/path/to"]

solved the issue. 解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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