从java执行终端命令 [英] Executing terminal commands from java
问题描述
我知道有很多线程,但没有一个为我工作。这里是我想做的:
I know there are many threads about this, but none of them worked for me. Here is what I am trying to do:
Javac并从我的java代码运行一个文件。它适用于Windows,但我想让它也在UNIX上工作。代码如下:
Javac and run a file from my java code. It works for Windows but I would like to make it also work on UNIX. Here the code:
if(os.equals("win")){
//For Windows
try {
Runtime.getRuntime().exec(
"cmd /c start cmd.exe /K "
+ "\"cd " + path + "&& "
+ "javac " + name + ".java && "
+ "echo ^>^>" + name + ".java " + "outputs: &&"
+ "echo. &&"
+ "java " + name + " && "
+ "echo. &&"
+ "pause && "
+ "exit\"");
} catch (IOException e) {
System.out.println("Didn't work");
}
}else{
try {
//TODO make it work for UNIX
Runtime.getRuntime().exec("");
} catch (IOException e) {
System.out.println("Didn't work");
}
}
问题是,在UNIX系统上,不可预测的
例如:
The problem is, that on UNIX systems it acts "unpredictable" For exemple:
Runtime.getRuntime().exec("open image.png");
打开图片,但
Runtime.getRuntime().exec("javac Test.java");
Runtime.getRuntime().exec("echo 'hello'");
它什么都不做。无按摩。
It does nothing. No Massage.
我非常感谢任何输入。
UPDATE ------ -------------------------------------------------- ----
看起来像Windows CMD,Terminal需要一个InputStreamReader来显示exec中发生的事情。我发现这个代码在另一个线程,现在至少我从exec终端的一些输出。
It seems like in contrast to Windows CMD, Terminal needs a InputStreamReader to display what happened in exec. I found this code in another thread and now at least I get some output from the exec Terminal.
String line;
Process p = Runtime.getRuntime().exec( "echo HelloWorld2" );
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
但是事情仍然是神秘的,因为执行
But things still remain misterious, because executing
Process p = Runtime.getRuntime()。exec(javac Test.java);
Process p = Runtime.getRuntime().exec("javac Test.java");
工作并生成Test.class文件。
works and generates a Test.class file. But
Process p = Runtime.getRuntime()。exec(javac Test.java& java Test); p>
Process p = Runtime.getRuntime().exec("javac Test.java && java Test");
不做任何事情(没有发生任何事情,终端执行没有错误按摩。)在Terminal中手动键入,建立并按预期运行。我缺少什么?
does nothing.(Nothing happens. Terminal "executes" without error massages.) Typing this manually in Terminal builds and runs as expected. What am I missing?
推荐答案
我没有Linux系统可以玩,上面的第二个命令试图编译名为Test.java,&&,java和Test的Java文件。换句话说,Runtime.exec()方法以字面方式处理参数,而不是应用shell解释。
I don't have a Linux system here to play with, but I'm pretty certain that the second command above is trying to compile Java files named "Test.java", "&&", "java" and "Test"; in other words the Runtime.exec() method treats arguments literally instead of applying shell interpretation.
您可能需要处理以下内容:
You could probably get it to work with something along the lines of:
Process p = Runtime.getRuntime().exec(
new String[] { "sh", "-c", "javac Test.java && java Test" });
这篇关于从java执行终端命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!