我创建如下程序以执行linux(raspbian)命令:“omxplayer”。
但是我不知道为什么在我将其输入命令行并按Enter时无法从omxplayer获得输出,但是输出仅显示在视频末尾。
因此,我想在输入“omxplayer [video_name]”并在程序中单击“Enter”后立即获得输出。
就像命令行(终端)在我在Linux中直接键入时一样。
这是我的代码:

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

        String in = "";
        while(in!="exit")
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            in = reader.readLine();
            runCommand(in);
        }
    }

    public static void runCommand(String command)
    {
           String s;
         Process p;
         try {
             System.out.println("run command " + command);
             p = Runtime.getRuntime().exec(new String[]{"bash", "-c",command});

             MyInputStreamReader reader1 = new MyInputStreamReader(p.getInputStream());
             reader1.setTag("in");
             reader1.start();

             MyInputStreamReader reader2 = new MyInputStreamReader(p.getErrorStream());
             reader2.setTag("in");
             reader2.start();


             p.waitFor();
             System.out.println ("exit: " + p.exitValue());
             p.destroy();
         } catch (Exception e) {}

    }
}

class MyInputStreamReader extends Thread{
    boolean isStop = false;
    ReadEventHandler handler;
    String tag;
    InputStream in;
    public MyInputStreamReader(InputStream in)
    {
        this.in = in;
    }

    public void setHandler(ReadEventHandler handler) {
        this.handler = handler;
    }
    public void setTag(String tag)
    {
        this.tag = tag;
    }

    public void run()
    {
        byte[] buff = new byte[8192];
        while (true) {
            //String line;
            try {
                int len  = in.read(buff);
                if (len == -1)
                {
                    return;
                }

                String line = new String(buff, 0, len);
                if (handler!=null)
                    handler.onReceived(line);
                System.out.println(tag +" " + line);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
    public void dispose()
    {
        this.isStop = true;
    }
    public interface ReadEventHandler
    {
        void onReceived(String line);
    }
}

高度赞赏任何回应。谢谢

最佳答案

你检查了吗?

http://javedmandary.blogspot.com/2014/01/firing-up-raspberry-pi-omxplayer-using.html

我想您正在寻找的代码。

08-28 05:09