歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

java執行linux命令

public class LinuxUtils {

static Logger logger = Logger.getLogger(LinuxUtils.class);

public static String exeCmd(String cmd) {

logger.info(cmd);

String returnString = "";

Runtime runTime = Runtime.getRuntime();

Process pro = null;

StringBuffer sb = new StringBuffer();

if (runTime == null) {

logger.error("Create runtime faliure!");

}

try {

pro = runTime.exec(cmd);

BufferedReader input = new BufferedReader(new InputStreamReader(

pro.getInputStream()));

String line;

while ((line = input.readLine()) != null) {

sb.append(line + "\n");

}

returnString = sb.toString();

logger.info("執行"+cmd+"命令的結果是:"+returnString);

input.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return returnString;

}

}

String ls = LinuxUtils.exeCmd("ls -l " + path);

char fc = ls.charAt(0);

opq = ls.substring(1, 10);

logger.info("執行linux命令的返回結果的第一個字符是:"+fc);

Copyright © Linux教程網 All Rights Reserved