简体   繁体   中英

How to run Java command through code?

I am trying to execute the below code

String command="cmd /c ls";
String location="C:\\project";

final Process process = Runtime.getRuntime().exec(
     dosCommand + " " + location);

I am getting the files, but when I run the cmd /c java I didn't get the output.
my Java home is added to environment variables.
When I give Java in command prompt I am getting the Java related files. I am not getting through my program.

I assume you want to run a Java program throught command line in your Java program? Try this:

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java ...");

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

Assuming you use Java 1.5 or higher, I'd recommend using ProcessBuilder if you want to execute from a different path. It allows you to easily set the working directory for the process.

final Process pr = new ProcessBuilder(
    "java", 
    "-Xms512M",
    "-Xmx1024M",
    "-jar", 
    "your_jar_to_use.jar", 
    "your Java class") 
    .directory(new File("<your directory>")) //Set the working directory to <your directory> 
    .start();

或者更好的方法是使用Java Compiler API,如本文本文件中所示

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