【问题标题】:How to execute the c executable file which takes input from file using java?如何执行使用java从文件中获取输入的c可执行文件?
【发布时间】:2023-03-24 12:35:01
【问题描述】:

这就是我正在做的:

Runtime rt = Runtime.getRuntime();

Process proc = rt.exec("./Hello" + " < in.txt");

它从文件中获取输入并将其打印在stdout 上。但这并没有被执行。我该如何实现?

【问题讨论】:

    标签: java c executable


    【解决方案1】:

    尝试单独传递每个参数,而不是将整个命令组合成一个字符串:

    String[] cmd = {"./Hello","<","in.txt"};
    
     Runtime rt = Runtime.getRuntime();
     Process proc = rt.exec(cmd);
    

    希望这会有所帮助;

    【讨论】:

      【解决方案2】:

      我对此的看法是,您希望从已执行的命令中获取输出。在调用Runtime.exec("&lt;some command&gt;")时,Java 会设置其单独的 IO-Streams 来读取和写入执行的命令。

      如果你想将命令的结果打印到命令行,那么你可以这样做:

      public class Test {
      
      
          public static void main(String[] args) throws IOException
          {
              int read;
              byte[] buffer = new byte[1024];
              Process p = Runtime.getRuntime().exec("echo HELLO-THERE");
              InputStream is = p.getInputStream();
              while (is.available() > 0) {
                  read = is.read(buffer);
                  System.out.println(new String(buffer, 0, read, "UTF-8"));
              }
          }
      }
      

      产生这个:

      HELLO-THERE
      

      通常,在这种情况下,您最好阅读 java 文档:https://docs.oracle.com/javase/7/docs/api/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-16
        • 1970-01-01
        相关资源
        最近更新 更多