简体   繁体   English

在Java中的Linux上的文件夹内运行进程

[英]Running a process inside a folder on Linux in Java

So I have a JAR program that runs and reads the output of a command line Linux app. 因此,我有一个运行并读取命令行Linux应用程序输出的JAR程序。 This app is located in a temp folder, which is where my JAR is. 这个应用程序位于一个临时文件夹中,这是我的JAR文件所在的位置。

Here's the Java code for reading the output: 这是读取输出的Java代码:

Process proc;
ProcessBuilder pb = new ProcessBuilder();
pb.command("temp/myapp", "arg1");
pb.redirectErrorStream(true);
try {
     proc = pb.start();
} catch (IOException ex) {
    System.out.println("ERROR: Couldn't start process");
}
scan = new Scanner(proc.getInputStream());
String line = "";
while (scan.hasNext())
      line += scan.nextLine() + System.lineSeparator();
scan.close();

Later I return that String I read into of course. 稍后,我当然会返回该字符串。

Now, the problem is that Scanner throws a NullPointerException, which means that the process cannot be found or cannot be run. 现在,问题在于Scanner抛出NullPointerException,这意味着找不到或无法运行该进程。 The moment I take the executable out of the temp and use 我暂时退出可执行文件并使用它的那一刻

pb.command("./myapp", "arg1");

My program works perfectly fine. 我的程序运行正常。

If I open Terminal where the JAR is, temp/myapp arg1 will return exactly what it should. 如果我在JAR所在的位置打开终端,则temp/myapp arg1将完全返回其应有的状态。 It's only the Java code that cannot seem to run this inside temp. 只是Java代码似乎无法在temp中运行此代码。

The question is, how do I point at the CLI app inside temp, if not the way I described above? 问题是,如果不是我上面描述的方式,我如何指向temp内部的CLI应用程序?

PS: The Java app works on Windows in the same setup, using pb.command("temp/myapp", "arg1") and a Win version of myapp so this is a Linux-specific issue. PS:Java应用程序可以在Windows上使用pb.command(“ temp / myapp”,“ arg1”)和Winapp版本的myapp在相同的设置下运行,因此这是特定于Linux的问题。

I think it is not getting the process at respective path. 我认为这并没有按照各自的路径进行。 Try by giving the absolute path of the process and then execute. 尝试给出过程的绝对路径,然后执行。 Hope it will work. 希望它能工作。

I found the solution. 我找到了解决方案。

ProcessBuilder's directory() method, which I also use somewhere, sets not only the working directory of the Process, but also the directory where the Process will be launched from, on Linux at least, so how my code was actually parsed on Linux was temp/temp/myapp . 我至少在Linux上也使用ProcessBuilder的directory()方法,它不仅设置了Process的工作目录,还设置了要从中启动Process的目录,所以我在Linux上实际解析代码的方式是temp/temp/myapp When I set temp as the working directory, I only had to use ./myapp to launch it from temp. 当我将temp设置为工作目录时,只需使用./myapp从temp启动它。 On Windows (my primary platform), this is not the case, I still have to use pass temp/myapp as parameter in command(). 在Windows(我的主要平台)上,不是这种情况,我仍然必须使用pass temp/myapp作为command()中的参数。

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

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