在做项目的过程中,有时候使用命令行会更加的简易。话不多说贴代码。
/**
* 通过命令解析文件内的内容
*
* @param cmd 命令
*/
public void execLinuxCmd(String cmd) {
if (CommonUtils.isNullOrEmpty(cmd)) {
return;
}
try {
Process pro = Runtime.getRuntime().exec(cmd);
pro.waitFor();
InputStream in = pro.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = read.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
通过传入cmd命令调用改方法,实际上是通过Runtime这个类,应用程序本身可以与其所在的环境进行通信。
通过该getRuntime()
方法提取与我们的应用程序关联的运行时,我们可以使用该exec()
方法直接执行命令或运行.bat
/.sh
文件。
/* 执行包含在command单独进程中的命令。 */
public Process exec(String command)
在后面执行的时候遇到了一个问题,当需要在命令中先进入文件所在目录再进行执行,一开始使用这个方法通过&&的方式连接两条命令,如下
cd /d C:\Users\xxx&&go build xxx.go
运行后程序报错
java.io.IOException: Cannot run program "'cd": CreateProcess error=2, 系统找不到指定的文件。
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at java.lang.Runtime.exec(Runtime.java:620)
at java.lang.Runtime.exec(Runtime.java:450)
at java.lang.Runtime.exec(Runtime.java:347)
at com.wiiot.api.utils.FileUtil.execLinuxCmd(FileUtil.java:162)
后来想到了exec()方法的另一个重载
/* command从dir目录中执行带有指定环境变量的。*/
public Process exec(String command, String[] envp, File dir)
于是又进行了一次封装
/**
* 在指定目录下执行命令
* @param cmd
* @param dir
*/
public void execCmdWithDir(String cmd,String dir) {
if (CommonUtils.isNullOrEmpty(cmd)||CommonUtils.isNullOrEmpty(dir)) {
return;
}
try {
Process pro = Runtime.getRuntime().exec(cmd,null,new File(dir));
pro.waitFor();
InputStream in = pro.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = read.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Tips:顺便记录一下通过System类获取操作系统名称的过程
System.getProperty("os.name")
这里获取操作系统的名称是为了用于判断程序运行时所处的环境再去执行对应的命令行