简体   繁体   English

如何通过代码运行Java命令?

[英]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. 我正在获取文件,但是当我运行cmd / c java时却没有得到输出。
my Java home is added to environment variables. 我的Java主页已添加到环境变量。
When I give Java in command prompt I am getting the Java related files. 当我在命令提示符下输入Java时,我正在获取与Java相关的文件。 I am not getting through my program. 我没有通过我的程序。

I assume you want to run a Java program throught command line in your Java program? 我假设您想通过Java程序中的命令行运行Java程序? Try this: 尝试这个:

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

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html 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. 假设您使用Java 1.5或更高版本,如果要从其他路径执行,建议使用ProcessBuilder。 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,如本文本文件中所示

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

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