package com.base.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class ShellUtil {
private String getOs(){
return System.getProperty("os.name");
}
/** Returns null if it failed for some reason.*/
public ArrayList<String> execCommand(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while( (line = br.readLine()) != null ) {
output.add(line);
}
//There should really be a timeout here.
if (0 != process.waitFor()) {
return null;
}
return output;
} catch (Exception e) {
//Warning: doing this is no good in high quality applications.
//Instead, present appropriate error messages to the user.
//But it's perfectly fine for prototyping.
return null;
}
}
public ArrayList<String> execCommandAllPlatforms(String cmdline){
if(getOs().contains("Mac OS X")){
return null;
}
return execCommand(cmdline, ".");
}
public String getLocalIp(){
String command="ifconfig eth0 | grep \"inet\\ \"| awk '{ print $2}'";
if(getOs().contains("Mac OS X")){
command="ifconfig en0 | grep \"inet\\ \" | awk '{ print $2}'";
}
return execCommand(command, ".").get(0);
}
}
测试代码
package com.service;
import com.base.utils.ShellUtil;
public class MainTest {
public static void main(String[] args) {
testShell();
}
public static void testShell(){
ShellUtil shellUtil = new ShellUtil();
System.out.println("IP:"+shellUtil.getLocalIp());
}
}