使用java执行shell命令时与进程通信

时间:2017-09-19 07:12:14

标签: java linux shell ubuntu darknet

我要从java执行shell命令,我需要在执行命令时将参数传递给输出流。

以下是shell命令

./darknet detect cfg/yolo-voc.2.0.cfg backup/yolo-voc_20000.weights

当执行此命令时,它正在为终端中的图像文件的路径屈服,我可以提供图像的路径,如下所示

Loading weights from backup/yolo-voc_21000.weights...Done!
Enter Image Path:

从终端执行时,我可以在那里提供路径。

我设法使用java进程执行此命令,并且当我使用命令提供图像uri时我也可以获得输出。这是代码

     public static void execCommand(String command) {
    try {

        Process proc = Runtime.getRuntime().exec(command);
        // Read the output
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line = "";
         //reader.readLine();
        while ((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
            s.add(line);
        }
//            proc.waitFor();
    } catch (IOException e) {
        System.out.println("exception thrown: " + e.getMessage());
    } 
}

但我想要的是在运行时提供图像路径而不是执行命令的开始。 尝试写入输出流,如下所示仍然没有运气

public static void execCommand(String command) {
    try {
        Process proc = Runtime.getRuntime().exec(command);
        // Read the output
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line = "";
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
             writer.append("data/test2.jpg");
          writer.newLine();
         //reader.readLine();
        while ((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
            s.add(line);
        }
//            proc.waitFor();
    } catch (IOException e) {
        System.out.println("exception thrown: " + e.getMessage());
    } 
}

1 个答案:

答案 0 :(得分:0)

您需要致电writer.flush(),以便将实际内容输出到下划线InputStream

因此,您的代码应如下所示:

public static void execCommand(String command) {
    try {
        Process proc = Runtime.getRuntime().exec(command);

        // Read the output
        BufferedReader reader = new BufferedReader(new 
            InputStreamReader(proc.getInputStream()));

        String line = "";
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
        writer.append("data/test2.jpg");
        writer.newLine();
        // **** add flush here ****
        writer.flush();
        // and remember to close your resource too
        writer.close();
        //reader.readLine();
        while ((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
            s.add(line);
        }
        // ***** close your reader also ****
        reader.close();
        //            proc.waitFor();
    } catch (IOException e) {
        System.out.println("exception thrown: " + e.getMessage());
    } 
}