Create a file using Runtime.exec using echo in linux?

对着背影说爱祢 提交于 2019-12-20 02:47:19

问题


I'm having trouble using Runtime.exec in Java, it seems some commands work while others do not. For example if I run

echo some data > data.txt

In my terminal it works fine, however if I try and use Java to do this it doesn't work.

Runtime mRuntime = Runtime.getRuntime();
Process mProcess = mRuntime.exec("echo some data > data.txt");
mProcess.waitFor();

Is there any reason for this?


回答1:


echo is not a real command in the sense that it has a binary that you can run. It is a built-in function of shells.

You could try running a shell like cmd.exe in Windows or sh in Linux/Mac/Unix, and then passing the command to run as a string.. Like using 'bash', you can do this:

edit because redirection is a little different using Runtime

To do redirection correctly, you should be using the form of exec that takes a String[].

Here's a quick example that does work with redirection.

public class RunTest {
   public static void main(String[] args) throws Exception {
      String [] commands = { "bash", "-c", "echo hello > hello.txt" };
      Runtime.getRuntime().exec(commands);
   }
}

But if you just wanted to create a file, you could create the file with Java's own API rather than use Runtime.




回答2:


That is because echo is a shell internal command not a program that can be executed! Try running instead bash -c "echo some data > data.txt"



来源:https://stackoverflow.com/questions/5914045/create-a-file-using-runtime-exec-using-echo-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!