如何用java代码模拟linux系统下的命令
例如 我要进入某个目录 在linux下我直接敲字符 cd /bin/usr/test
在java中如何用代码来实现这个操作,拜托大佬们给小弟解解惑!
如何用java代码模拟linux系统下的命令
例如 我要进入某个目录 在linux下我直接敲字符 cd /bin/usr/test
在java中如何用代码来实现这个操作,拜托大佬们给小弟解解惑!
Java 提供了调用 Linux 命令的方法:
public static List<String> executeComm(String comm){
List<String> strList = new ArrayList<String>();
Process process = null;
BufferedReader in = null;
try {
//整个命令作为sh的参数进行执行,以便执行重定向和管道命令,否则管道命令会被当成参数执行,得到错误结果
String[] arr = new String[]{"/bin/sh", "-c", comm};
process = Runtime.getRuntime().exec(arr); // 执行添加权限的命令
process.waitFor(); // 如果执行多个命令,必须加上
in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String str = null;
while ((str = in.readLine()) != null) {
strList.add(str);
}
} catch (IOException e) {
logger.error("执行 Shell 时,出现IO异常,设置失败",e);
} catch (InterruptedException e) {
logger.error("设置 IP 时,出现InterruptedException异常,设置失败",e);
}finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
logger.error("关闭输入流失败",e);
}
}
if(process != null){
process.destroy();
}
}
return strList;
}
自己写个main 方法,把 日志打印的换成 System.out 。调用参数为 cd /dir