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.

2
  • Possible duplicate of Call c function from Java Commented Apr 22, 2018 at 0: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. Commented Apr 22, 2018 at 1:01

1 Answer 1

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.