我正在尝试运行以下代码,但无法正常工作,有人可以帮助我了解为什么它会这样运行,还是我丢失了某些东西?
import java.io.IOException;
public class SimpleClass {
public static void main(String args[]){
try {
Process process = Runtime.getRuntime().exec("bash mkdir demoDir");
// Process process2 = Runtime.getRuntime().exec("echo sometext >> someFile.txt");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
如果我执行第一个进程,则工作正常,但如果我执行process2,则工作不正常。存在someFile.txt和当前的工作目录,除此命令外,如果我尝试创建像mkdir /home/dummy/demoDir
这样的目录,则它也无法工作,但我的程序成功执行。
>>
由您的shell解释和处理(例如bash,zsh等)。但是,您没有在此命令中运行Shell。 Runtime.exec()
基本上执行命令/bin/echo
,并向其传递参数someText
,>>
,someFile.txt
。
我不知道为什么你想做自己正在做的事情,但是尝试一下:
Runtime.getRuntime().exec("bash -c \"echo sometext >> someFile.txt\"");
这个问题的答案已经讨论here。使用
String[] cmd = {"bash", "-c", "echo sometext >> someFile.txt" };
Process process2 = Runtime.getRuntime().exec(cmd);
相反。为我工作。
没有外壳,您将无法执行echo命令->在开头添加bash