关于java:读取命令的实时输出 | 珊瑚贝

Read realtime output of a command


如何从 Java 读取 shell 命令的实时输出

这是我目前所拥有的,但它在命令执行后打印:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
try {
    proc = Runtime.getRuntime().exec(“du -d 1 /sdcard/”);

    InputStream inputStream = proc.getInputStream();
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

    while ((line = bufferedReader.readLine()) != null) {
        publishProgress(i);
        i++;
        System.out.println(line); // it prints all at once after command has been executed.
    }
}
catch (IOException e) {
    Log.e(“du”,“error”+e.getMessage());
}

  • 顺便说一句,您在哪里看到 System.out.println 的输出?
  • 你的输出中只有一行吗?
  • du 非常快。然而,你尝试过 ProcessBuilder 和 Process.start 吗?
  • @pedja 在 LogCat 中,您会看到 Log 方法的输出,而不是 System.out.println
  • 不,它的命令 du 来自 linux。扫描整个文件夹并显示大小
  • @fiddler 它也打印 System.out.println
  • @pedja 哦,您说的是已弃用的 LogCat 视图
  • System.out.println 不是问题。在 onProgressUpdate 中更新 ui 也会发生同样的情况
  • 我在 Windows 上测试了你的代码,它立即打印输出


试试这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try {
 proc = Runtime.getRuntime().exec(“du -d 1 /sdcard/”);

 InputStream inputStream = proc.getInputStream();
 InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

 while ((line = bufferedReader.readLine()) != null) {
    System.out.println(line); // it prints all at once after command has been executed.
 }
 proc.waitFor();
}
catch (IOException e) {
 Log.e(“du”,“error”+e.getMessage());
}


来源:https://www.codenong.com/13530429/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9803.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?