简体   繁体   中英

Executing one Java program from another using Runtime.exec(…)

The tester program that I wanted execute takes in a single argument -- a filename -- and makes a copy of the file with the line "This is a modified version." at the top of the new file. When I tested this program alone, it works and produces a new file.

Then I wrote the program to call the file:

public static void main(String[] args) {
    try {
        Process p = Runtime.getRuntime.exec("java Tester.java inputfilename.txt");
        p.waitFor();
        System.out.println("Done");
    } catch(Exception e) {
        System.out.println("Error");
        System.exit(0);
    }
} 

The program above printed out "Done" but it never made a modified version of the file I passed in. I then put some println()'s in the other program. When I run that program alone, it printed out those statements, but when I tried to call it from the program above, it did not. How do I fix this?

You have to compile .java file first and launch it later:

Compile (class containing the main method):

javac Tester.java

Launch:

java Tester inputfilename.txt
"java Tester.java inputfilename.txt"

Should be:

"java Tester inputfilename.txt"

But do yourself a favor and read (and implement) all the recommendations of When Runtime.exec() won't .

That might solve other problems. If not, it should provide more information as to the reason for failure.

Then ignore that it refers to exec and build the Process using a ProcessBuilder . Also break a String arg into String[] args to account for arguments which themselves contain spaces.

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