需要使用.java.lang包下的 Process类
第一步:
定义好要执行的shell指令
例如:需要输入 python 1.py
来执行当前目录下的 1.py 文件,
则我们需要定义一个存储指令的String数组
String[] arguments = new String[] {"python", "1.py"};
第二步:
通过以下语句来执行shell指令,并返回一个Process对象:
Process process = Runtime.getRuntime().exec(arguments);
第三步
通过Process对象来获取执行结果
process.getInputStream();
示例代码:
public void test(){
String[] arguments = new String[] {"python", "1.py"};
BufferedReader bufferedReader = null;
try {
Process process = Runtime.getRuntime().exec(arguments);
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权声明:本文为qq_41542638原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。