【问题标题】:Having trouble calling .class to process on IntelliJ在 IntelliJ 上调用 .class 处理时遇到问题
【发布时间】:2021-12-02 05:30:29
【问题描述】:

我试图从 .class 中获取结果,并在另一个 .java 上调用该进程。两个文件的格式如下:

package Ejemplo2;

import java.io.*;

public class Ejemplo2 {

    public static void main(String[] args) throws IOException {

        Process p = new ProcessBuilder("ls", "-la").start();

        try {
            InputStream is = p.getInputStream();
            int c;
            while ((c = is.read()) != -1) {
                System.out.print((char) c);
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        int exitVal;
        try {
            exitVal = p.waitFor(); //recoge la salida de System.exit()
            System.out.println("Valor de Salida: " +exitVal);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

package Ejemplo3;

import java.io.*;

public class Ejemplo3 {

    public static void main(String[] args) throws IOException{

        File directorio = new File("./out/production/psp-2122/Ejemplo2");

        ProcessBuilder pb = new ProcessBuilder("java", "Ejemplo2");

        pb.directory(directorio);

        System.out.printf("Directorio de trabajo: %s%n",pb.directory());

        Process p = pb.start();

        try {
            InputStream  is = p.getInputStream();

            for (int i = 0; i<is.available(); i++) {
                System.out.println("" + is.read());
            }
            
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

结果只显示了目录和退出代码,但我真的不知道为什么没有显示进程本身。

【问题讨论】:

    标签: java intellij-idea


    【解决方案1】:

    你应该这样做:

    // start in classes root
    File directorio = new File("./out/production/psp-2122"); 
    // Run java with fully qualified class name Ejemplo2.Ejemplo2
    ProcessBuilder pb = new ProcessBuilder("java", "Ejemplo2.Ejemplo2"); 
    

    【讨论】:

      【解决方案2】:

      您没有看到任何错误消息,因为您没有阅读任何错误流。最简单的方法是在调用 start() 之前重定向标准 ERROR -> OUTPUT:

      ProcessBuilder pb = new ProcessBuilder(cmd);    
      pb.redirectErrorStream(true);
      Process p = pb.start();
      

      节省一些输入,将标准输出流中的 while / for 循环替换为:

      try(var stdout = p.getInputStream()) {
          stdout.transferTo(System.out);
      }
      

      始终在最后调用waitFor,以便您知道流程完成:

      int exitVal = pb.waitFor();
      

      【讨论】:

        猜你喜欢
        • 2020-02-27
        • 2016-01-04
        • 2020-10-06
        • 1970-01-01
        • 1970-01-01
        • 2017-01-08
        • 2011-09-20
        • 2014-12-03
        • 2018-10-07
        相关资源
        最近更新 更多