利用Java的Runtime获取到JVM运行环境,当项目部署到Linux上时,即可通过exec方法执行sh文件了。
package com.xiaowuqin;
import java.io.IOException;
import java.io.InputStream;
public class ProcessDemo {
private Process process;
public ProcessDemo(String command) throws IOException, InterruptedException {
process=Runtime.getRuntime().exec(command);
int i = process.waitFor();
}
public InputStream getResult(){
return this.process.getInputStream();
}
}
package com.xiaowuqin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
String shp="/bin/bash /opt/a.sh";
String command=shp;
ProcessDemo processDemo = new ProcessDemo(command);
InputStream result = processDemo.getResult();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(result));
System.out.println(bufferedReader.readLine());
}
}
踩坑点,在Linux上报错:
Error: Could not find or load main class
原因及解决:
当前目录是.class文件所在目录,要运行.class字节码文件,需要将当前目录加入系统变量CLASSPATH,系统才能找到当前目录下的Java类。