问题描述
我现在在linux机器上。我有一个Java程序可以运行一些linux命令,例如 ps
, top
, list
或 free -m
。
I am now on a linux machine. I have a Java program which would run some linux command, for example ps
, top
, list
or free -m
.
在Java中运行命令的方法如下:
The way to run a command in Java is as follows:
Process p = Runtime.getRuntime().exec("free -m");
我如何通过Java程序收集输出?我需要处理输出中的数据。
How could I collect the output by Java program? I need to process the data in the output.
推荐答案
使用表示新创建的进程的标准输出。
Use Process.getInputStream()
to get an InputStream
that represents the stdout of the newly created process.
请注意,从Java启动/运行外部进程可能非常棘手并且非常复杂一些陷阱。
Note that starting/running external processes from Java can be very tricky and has quite a few pitfalls.
它们在,也介绍了解决这些问题的方法。
They are described in this excellent article, which also describes ways around them.
这篇关于收集Linux命令输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!