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

來源:互聯網
上載者:User

最近項目需要檢測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系統中的控制台上輸入這個命令的話,是有值的,一直沒搞明白為什嗎?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.