多的不说,这些名词都是很简单易懂的,直接上代码!
public String runbat(String batName) { String str = null; try { Process ps = Runtime.getRuntime().exec(batName); InputStream in = ps.getInputStream(); byte[] sb = readStream(in); str = new String(sb, "UTF-8"); System.out.println(str); in.close(); ps.waitFor(); } catch (Exception e) { e.printStackTrace(); } System.out.println("\nchild thread done"); return str; }
这里写下用到的工具方法,把流转成字符串输出:
public static byte[] readStream(InputStream inStream) throws Exception { ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); return outSteam.toByteArray(); }
注意
若会弹出cmd框,并且不能自动关闭,则在bat文件最后加上
exit
up
up
up