Create file using Runtime.exec?

I am having problems using Runtime.exec in Java, it seems that some commands work and others do not. For example, if I run

echo some data > data.txt

It works fine in my terminal, however, if I try to use Java for this, it does not work.

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

Is there a reason for this?

+3
source share
2 answers

echois not a real team in the sense that it has a binary that you can run. This is a built-in shell feature.

You can try to run a type shell cmd.exeon Windows or shLinux / Mac / Unix, and then pass the command to run as a string. As with 'bash', you can do this

, Runtime

, exec, String[].

, .

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

, API Java, Runtime.

+8

, echo - , , ! bash -c "echo some data > data.txt"

+1

All Articles