Runtime.getRuntime().exec()的用法

最近项目需要检测Linux系统下面的一个挂载情况,网上也找了很多资料,最终决定用Runtime.getRuntime().exec()这个关键方法来实现,以前也没咋写过博客,今天第一次学着写博客,请大家多批评指正

先上正确代码:

汗,请问要怎么粘贴代码上来? - -

package com.fajun.shell.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DoShell {

 private static boolean getShellReturn(String shell_cmd,String shell_result) throws IOException{
  
  Process process = Runtime.getRuntime().exec(shell_cmd);
  InputStream inputStream = process.getInputStream();
  InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  List<String> strings = new ArrayList<String>();
  String str = null;
  while ((str = bufferedReader.readLine())!= null) {
   strings.add(str);
  }
  for (int i = 0; i < strings.size(); i++) {
   if (strings.get(i).contains(shell_result)) {
    return true;
   }
  }
  
  return false;
  
}
 

private static  String getOSName(){
  
  Properties properties = System.getProperties();
  String os = properties.getProperty("os.name");
  return os;
  
}
 public static void main(String[] args) {
  String os = getOSName();
  if (os.contains("inux")) {
   
   String shell_cmd = "mount";
   String shell_result="sda1";
   boolean flag =false;
   try {
    flag = getShellReturn(shell_cmd, shell_result);
   } catch (IOException e) {
    e.printStackTrace();
   }
   System.out.println("the result is "+ flag);
  }
  System.out.println("os name is "+os);
  
}
}


以上就是我写的一个测试代码,请大家参考指正。

 

我写这个代码的过程中,出了一个问题,就是如果传入getShellResult()这个方法的是“mount | grep sda1”这样的精确查找的话,不能查出任何的内容,但是如果在linux系统中的控制台上输入这个命令的话,是有值的,一直没搞明白为什么?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值