从Java程序中运行bash命令 [英] Running a bash command from within a Java program
本文介绍了从Java程序中运行bash命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑一段Java代码:
Consider a piece of Java code:
import java.io.IOException;
public class Demo{
public static void main(String []args) throws IOException{
...
String abc="i am here";
System.out.println(abc);
}
}
我想运行-回显文件的文件名" >> file1.txt-假设file1.txt在同一目录中,紧接在System.out.println()行之后.
I want to run - echo "THIS IS STUFF FOR THE FILE" >> file1.txt - immediately after the System.out.println() line, assuming file1.txt is in the same directory.
推荐答案
ProcessBuilder
类是更现代的版本.
import static java.lang.ProcessBuilder.Redirect.appendTo;
ProcessBuilder pb = new ProcessBuilder("/bin/echo", "THIS IS STUFF FOR THE FILE");
pb.redirectOutput(appendTo(new File("file1.txt")));
Process p = pb.start();
请注意,这将直接调用/bin/echo
,而不是让 bash
浏览 PATH
.这样比较安全,因为没有机会遭到黑客入侵 echo
.另外,由于它不使用 bash
,因此Java用于重定向输出.
Notice that this calls /bin/echo
directly instead of having bash
look through the PATH
. That's safer, as there is no chance of getting a hacked echo
. Also, since this doesn't use bash
, Java is used to redirect the output.
这篇关于从Java程序中运行bash命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文