简体   繁体   English

使用Java的输入和输出重定向调用C可执行文件

[英]Call a C executable with input and output redirection from Java

I have the following Folder structure: 我具有以下文件夹结构:

  • Project 项目
    • Lexer Lexer
      • mylexer (this is a C executable program) mylexer(这是C可执行程序)
  • Parser 解析器
    • MyJavaFile.java MyJavaFile.java

From the java file in parser I want to execute the mylexer program and wait for a result. 从解析器中的Java文件中,我要执行mylexer程序并等待结果。 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"}; 我没有得到任何结果,程序永远不会结束执行,如果执行此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. 但这在Java上不起作用。

Input and output redirection using < and > are performed by the shell (sh, bash, or whatever you're using). 使用<>输入和输出重定向由外壳程序(sh,bash或您使用的任何东西)执行。 They're not available in ProcessBuilder with this syntax, unless you invoke the shell from ProcessBuilder. 除非您从ProcessBuilder调用外壳程序,否则它们不能在ProcessBuilder中使用此语法。

However ProcessBuilder has its own support for redirecting input and output of the process that it starts using the redirectInput and redirectOutput methods. 但是,ProcessBuilder对其使用redirectInputredirectOutput方法开始的进程的输入和输出进行重定向具有自己的支持。 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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM