1

我将从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());
    } 
}
4

1 回答 1

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());
    } 
}
于 2017-09-19T08:06:29.300 回答