简体   繁体   中英

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. This app is located in a temp folder, which is where my JAR is.

Here's the Java code for reading the output:

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. 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. It's only the Java code that cannot seem to run this inside temp.

The question is, how do I point at the CLI app inside temp, if not the way I described above?

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.

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 . When I set temp as the working directory, I only had to use ./myapp to launch it from temp. On Windows (my primary platform), this is not the case, I still have to use pass temp/myapp as parameter in command().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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