0

I have the following Folder structure:

  • Project
    • Lexer
      • mylexer (this is a C executable program)
  • Parser
    • MyJavaFile.java

From the java file in parser I want to execute the mylexer program and wait for a result. I have the following code:

public static String getTokensFromFile(String path) {
    String s = null;
    StringBuilder sb = new StringBuilder(path);
    try {
        Runtime rt = Runtime.getRuntime();
        String[] command = {"mylexer", "<", path, ">", "output.txt"};
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.directory(new File("../Lexer"));
        Process pr = pb.start();
        BufferedReader stdInput = new BufferedReader(new
             InputStreamReader(pr.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
             InputStreamReader(pr.getErrorStream()));
        while ((s = stdError.readLine()) != null) {
            sb.append(s+"\n");
        }
    }catch(Exception e) {
        System.out.println(e);
    }
    return (sb.toString().length() > 0)? sb.toString() : "";
}

I didn't get any result, the program never ends the execution, and if I do this String[] command = {"./mylexer", "<", path, ">", "output.txt"}; It says that The file is not found. How can I achieve that?

Also I did this on my terminal

../Lexer/mylexer < /Users/jacobotapia/Documents/Compiladores/Proyecto/Lexer/sample.txt > output.txt 

But this don't work on Java.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
Jacobo
  • 1,259
  • 2
  • 19
  • 43
  • Possible duplicate of [Call c function from Java](https://stackoverflow.com/questions/5963266/call-c-function-from-java) – Logan Apr 22 '18 at 00:43
  • Imho, it might be a duplicate, but not of said question. AFAIK, ProcessBuilder will not automatically generate input/output redirection from "<" and ">". That's a shell feature. You have to either manage the Streams from Java, or call a shell script, which does the redirection. That script could be parameterized with 'path' as $1 which should be the simplest solution. – user unknown Apr 22 '18 at 01:01

1 Answers1

2

Input and output redirection using < and > are performed by the shell (sh, bash, or whatever you're using). They're not available in ProcessBuilder with this syntax, unless you invoke the shell from ProcessBuilder.

However ProcessBuilder has its own support for redirecting input and output of the process that it starts using the redirectInput and redirectOutput methods. The following should work for you:

String[] command = {"mylexer"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectInput(new File(path));
pb.redirectOutput(new File("output.txt"));
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79