浏览 2000 次
锁定老帖子 主题:java调用系统命令
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-08-13
简单的静态函数 SysCmd.java: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SysCmd { public static String autoExec(String cmdLine) throws IOException, InterruptedException { if (System.getProperty("os.name").matches(".*[Ww]indows.*")) { return exec(new String[] { "cmd", "/c", cmdLine }); } else { return exec(new String[] { "sh", "-c", cmdLine }); } } public static String exec(String[] cmdArray) throws IOException, InterruptedException { Process p = Runtime.getRuntime().exec(cmdArray); String line = null; StringBuffer result = new StringBuffer(); BufferedReader brIn = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = brIn.readLine()) != null) { result.append(line + "\n"); } brIn.close(); BufferedReader brErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = brErr.readLine()) != null) { result.append(line + "\n"); } brErr.close(); return result.toString(); } }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |