Home > Software design >  Having a hard time with linux command calls in Java with exec()
Having a hard time with linux command calls in Java with exec()

Time:11-03

I'm trying to use Runtime.getRuntime().exec() to call a program as if it was called from the terminal, but it just crashes with a fatal error after reading the first file.

In the terminal I run the command like so:

mace4 -c -f inputFile.in > outputFile.out

It works as expected, reading from the first file and outputting in the second one.

In Java I try to run it this way:

String args[] = new String[]{"mace4", "-c", "-f", inputFileName ,">",outputFileName};
        try {
            String s;
            Process proc = Runtime.getRuntime().exec(args, null, new File("/home/user/workDirectory/"));
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(proc.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: "   s);
            proc.waitFor();
            proc.destroy();

As soon as the program reaches the end of the first file, it throws this:

Fatal error: read_all_input, file > not found

The program is quite old and I can't seem to find a way to get a more detailed error out of it..

I tried calling it with these arguments {"sh or bash", "-c", "mace4", "-c", "-f", inputFileName ,">",outputFileName} which makes the program run and then freeze (or at least nothing appears in the console).. Am I calling the terminal command wrong and if yes what should I change?

PS: this is my first question here, if I missed anything, I'm sorry..

CodePudding user response:

It looks like you're trying to use the Bash output redirection operator >. This redirects the output of the program you're running to a file (or another program)

This answer explains how to do this using ProcessBuilder which should work for what you're trying to do here.

For example:

ProcessBuilder pb = new ProcessBuilder("mace4", "-c", "-f", inputFileName);
pb.redirectOutput(new File(outputFileName));
Process p = pb.start();
  • Related