So i have two files: Main.java and Second.java. I wanna work with processes using ProcessBuilder. With cmd i can write "javac Second.java" and "java Second 5". My Second.java looks like that
public static void main(String[] args) {
System.out.println("Okay");
System.out.println(Integer.parseInt(args[0])); // I need it just for checking
System.exit( Integer.parseInt(args[0]));
}
My second process should return specific exit value (that's why i use System.exit() ). I understood that ProcessBuilder is not a cmd. I tried to run it like that
Path currentRelativePath = Paths.get("");
String curDir=currentRelativePath.toAbsolutePath().toString();
curDir=curDir "\\src";
ProcessBuilder PB=new ProcessBuilder("java",curDir, "second", "5");
try {
Process process = PB.start();
process.waitFor();
System.out.println(process.exitValue());
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But that doesn't work. I think i don't need to create class files exactly in my program i will create them later by cmd. How can i give my ProcessBuilder String[] args, which i need in my Second.main()?
CodePudding user response:
You are executing this command: java directory second 5
That is not a valid invocation of the java
command. The syntax is:
java
[-options] class [args...]
Passing a class name is correct. Passing a directory is not correct.
You can see the syntax for yourself by running java -h
, or by reading the documentation. No need to guess what is allowed.
What you are allowed to do is pass a directory as an argument to the -cp
option, which is probably what you intended:
new ProcessBuilder("java", "-cp", curDir, "second", "5");
Be aware that class names are case sensitive. If your class is named Second
, you must pass the same name, with a capital S
, to your java command:
new ProcessBuilder("java", "-cp", curDir, "Second", "5");
↑
Uppercase S
All file paths are either absolute paths, or are implicitly relative to the current directory. You don’t need all those lines dealing with currentRelativePath
. Just write this:
String curDir = "src";