Home > Net >  Executing cat ./file1.txt file2.txt >> merged.txt fails with java.lang.RuntimeException: cat:
Executing cat ./file1.txt file2.txt >> merged.txt fails with java.lang.RuntimeException: cat:

Time:10-06

I'm trying to execute this Linux command from Java: cat ./file1.txt ./file2.txt >> ./merged.txt

Runtime.getRuntime().exec("cat", "FULLPATH/file1.txt", "FULLPATH/file2.txt", ">>", "FULLPATH/merged.txt");

This works directly in the console but fails in Java:

java.lang.RuntimeException: cat: >: No such file or directory
cat: FULLPATH/merged.txt: No such file or directory

Do you know how to fix it?

CodePudding user response:

Redirection >> is a feature of your shell so you need to run under that shell. Java process launch cannot handle. Try calling your shell to handle the command such as say:

String []cmd = new String[] {"/bin/bash", "-c", "cat ... >> xyz.txt"};

Alternatively use ProcessBuilder with file redirectOutput for saving standard output to a file and drop the ">>" part, and you may need to use full pathname to the cat executable if that is not on the PATH of JVM.

String []cmd = new String[] {"cat", "path1", "path2"};
  •  Tags:  
  • java
  • Related