如何从Java调用格式化的linux shell命令?

时间:2016-06-15 06:35:24

标签: java linux

我正在使用java代码在Linux上跟踪磁盘使用情况的项目。我执行了以下代码

public  void checkSystemPerformance() {
    System.out.println( "------- Track Disk Usage -------" );

        BufferedReader stdInput  = null;
        BufferedReader stdError = null;
        String line = "";

        try {
            String diskUsageCommandTest = "df -h";
            //String diskUsageCommandTest = "df -h | awk '$NF==\"/\"{printf \"Disk Usage: %d/%dGB (%s)\n\", $3,$2,$5}'";I want the result of this command via java code

            Process proc = Runtime.getRuntime().exec(diskUsageCommandTest);

            stdInput  =  new BufferedReader(new InputStreamReader(proc.getInputStream()));
            stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while((line = stdInput .readLine()) != null) {
                System.out.println(line);
            }

            // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((line = stdError.readLine()) != null) {
                System.out.println(line);
            }

            proc.waitFor();   

            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
        }
    }

我得到以下输出:

------- Track Memory Usage,Disk Usage and CPU Load -------
Here is the standard output of the command:

Filesystem                   Size  Used Avail Use% Mounted on
/dev/mapper/ubuntu--vg-root   19G   16G  2.3G  88% /
udev                         987M  4.0K  987M   1% /dev
tmpfs                        200M  268K  200M   1% /run
none                         5.0M     0  5.0M   0% /run/lock
none                         998M     0  998M   0% /run/shm
/dev/sda1                    236M   33M  191M  15% /boot
Here is the standard error of the command (if any):

我已经通过java代码

在线下执行了
String diskUsageCommandTest = "df -h | awk '$NF==\"/\"{printf \"Disk Usage: %d/%dGB (%s)\n\", $3,$2,$5}'";

我得到以下输出:

------- Track Memory Usage,Disk Usage and CPU Load -------
Here is the standard output of the command:

Here is the standard error of the command (if any):

df: `|': No such file or directory
df: `awk': No such file or directory
df: `\'$NF=="/"{printf': No such file or directory
df: `"Disk': No such file or directory
df: `Usage:': No such file or directory
df: `%d/%dGB': No such file or directory
df: `(%s)': No such file or directory
df: `",': No such file or directory
df: `$3,$2,$5}\'': No such file or directory
df: no file systems processed

在linux终端上,我运行以下命令:

df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'

我得到以下输出:

Disk Usage: 16/19GB (88%)

所以任何人都知道我可以在java代码中做什么来获得格式的输出,例如"磁盘使用率:16 / 19GB(88%)"?

3 个答案:

答案 0 :(得分:0)

你可以看看here,这可以解决你的问题 - 如果你的情况可能(用你的命令创建一个shellcript并执行那个)

答案 1 :(得分:0)

Java exec需要一个命令,当你为它提供所有管道时,它试图找到一个名为df -h | awk '$NF==\"/\"{printf \"Disk Usage: %d/%dGB (%s)\n\", $3,$2,$5}'";的命令,该命令不存在(在shell中尝试自己,在双引号内输入命令)。

所以你需要的是用这个命令创建一个shell脚本或者执行例如bash -c "your command"

Process proc = Runtime.getRuntime().exec("bash", "-c", diskUsageCommandTest);

答案 2 :(得分:0)

也许你不需要为它调用shell命令。请看下面的代码片段。

double freeSpace = Math.round(root.getFreeSpace() / 1024D / 1024 / 1024);
double totalSpace = Math.round(root.getTotalSpace() / 1024D / 1024 / 1024);
long usedSpace = (long) (totalSpace - freeSpace);
int percentage = (int) ((usedSpace * 100) / totalSpace);
System.out.printf("Disk Usage: %d/%dGB (%d%%)%n",
        usedSpace,
        (int) totalSpace,
        percentage
);

注意:代码写为scratch。看看圆角是否合适。