我们有人用python,有人使用java写脚本(java脚本一般使用bat文件执行,如uiautomator脚本),所以我们只需区分是.py还是.bat的格式;
选择脚本后,点击“执行脚本按钮”,然后自动判断是什么后缀格式,一般我们常用脚本如.py\bat\.java\.h等;
执行逻辑,判断选择是否为空,为空弹出一个提示框,不为空时,非py和bat后缀,我们都认为不是脚本,也弹出提示
/* 这个是调用选择脚本路径,供其他位置调用此路径,如 */
private String getScriptFilePath() {
return textField_choose.getText().toString();
}
btnNewButton_zhixing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String path = getScriptFilePath();//选择脚本显示的路径,我自动获取,可以手动选择,这里不清楚看看我其他类似“文件路径选择”,如:d:\wifi.py
Process process1 = null;
StringBuilder result = new StringBuilder();
BufferedReader bufrIn = null;
BufferedReader bufrError = null;
String line = null;
// String path
// =textField_choose.getText().toString();//可以直接这么写,但是不太好,在外部调用方法;
try {
if(path.equals("")){
JOptionPane.showConfirmDialog(p,"请先选择可执行脚本","脚本为空",0);
}else{
/*判断不是.py||.bat,弹出提示*/
String docUrl = path;
String[] allowTypes = new String[] { "py","bat" };
int splitIndex = docUrl.lastIndexOf(".");
String fileType = docUrl.substring(splitIndex + 1);//py、bat等
/*fileType显示后缀格式*/
System.out.println("fileType:" + fileType);
if(fileType.equals("py" ) || fileType.equals("bat")){//非脚本弹出提示选择正确脚本,这块代码可以优化下,初学者可以先这么写
//判断是python脚本还是bat脚本
if(fileType.equals("py")){//python脚本
System.out.println("这是python脚本");
Process process11= Runtime.getRuntime().exec("python " + path);
// 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出(PS: 子进程的输出就是主进程的输入)
bufrIn = new BufferedReader(new InputStreamReader(process11.getInputStream(), "UTF-8"));
bufrError = new BufferedReader(new InputStreamReader(process11.getErrorStream(), "UTF-8"));
// 读取输出
while ((line = bufrIn.readLine()) != null) {
result.append(line).append('\n');
System.out.println("line1: "+line);
}
StringBuffer outputBuf = new StringBuffer();
while ((line = bufrError.readLine()) != null) {
result.append(line).append('\n');
System.out.println("line2: "+line);
String bc = line;
outputBuf.append(line);
outputBuf.append("\n");
}
showContent(outputBuf.toString());
}
if(fileType.equals("bat")){//bat脚本
System.out.println("这是bat脚本");
// Runtime.getRuntime().exec(path);
// 执行ping命令
Process process = Runtime.getRuntime().exec("cmd.exe /C start "+path);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("UTF-8")));
String line1 = null;
while ((line1 = br.readLine()) != null) {
System.out.println(line1);
}
}
}else{
JOptionPane.showConfirmDialog(p,"请先选择.py或.bat脚本文件","错误脚本",0);
}
}
} catch (Exception e2) {
// TODO: handle exception
}
}
});