本文目录
怎样在java代码中调用执行shell脚本
// 用法:Runtime.getRuntime().exec("命令"); String shpath="/test/test.sh"; //程序路径 Process process =null; String command1 = “chmod 777 ” + shpath; try { Runtime.getRuntime().exec(command1 ).waitFor(); } catch (IOException e1) { e1.printStackTrace(); }catch (InterruptedException e) { e.printStackTrace(); } String var="201102"; /参数 String command2 = “/bin/sh ” + shpath + ” ” + var; Runtime.getRuntime().exec(command2).waitFor();
windows下java怎样调用shell脚本文件
// 用法:Runtime.getRuntime().exec("命令"); String shpath="/test/test.sh"; //程序路径 Process process =null; String command1 = “chmod 777 ” + shpath; try { Runtime.getRuntime().exec(command1 ).waitFor(); } catch (IOException e1) { e1.printStackTrace(); }catch (InterruptedException e) { e.printStackTrace(); }String var="201102"; /参数 String command2 = “/bin/sh ” + shpath + ” ” + var; Runtime.getRuntime().exec(command2).waitFor();
怎么通过java去调用并执行shell脚本以及问题总结
import java.io.BufferedReader;import java.io.File;import java.io.InputStreamReader;import java.util.ArrayList;public class Shell { public static ArrayList《String》 command(final String cmdline, final String directory) { try { Process process = new ProcessBuilder(new String {"bash", "-c", cmdline}) .redirectErrorStream(true) .directory(new File(directory)) .start(); ArrayList《String》 output = new ArrayList《String》(); BufferedReader br = new BufferedReader( new InputStreamReader(process.getInputStream())); String line = null; while ( (line = br.readLine()) != null ) output.add(line); if (0 != process.waitFor()) return null; return output; } catch (Exception e) { return null; } } public static void main(String args) { test("which bash"); test("find . -type f -printf ’%T@\\\\t%p\\\\n’ " + "| sort -n | cut -f 2- | " + "sed -e ’s/ /\\\\\\\\ /g’ | xargs ls -halt"); } static void test(String cmdline) { ArrayList《String》 output = command(cmdline, "."); if (null == output) System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline); else for (String line : output) System.out.println(line); }}