当前位置: 技术问答>java相关
如何用java执行批处理文件(bat),不要小看,试试再说,谢谢!
来源: 互联网 发布时间:2015-05-23
本文导语: 如何用java执行批处理文件(bat),不要小看,试试再说,谢谢! | public static boolean spawnExe (String batch_file, boolean waitOnClose) { boolean retval = false; try { ...
如何用java执行批处理文件(bat),不要小看,试试再说,谢谢!
|
public static boolean spawnExe (String batch_file, boolean waitOnClose)
{
boolean retval = false;
try {
String osName = System.getProperty("os.name");
String[] cmd = new String[3];
// Win9X
if (osName.equals(WIN_95) ||
osName.equals(WIN_98) ||
osName.startsWith(WIN_3X) ||
osName.startsWith(WIN_FW) ) {
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = batch_file;
retval = true;
}
// W2K or greater
else if ( osName.startsWith(WIN) ) {
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = batch_file;
retval = true;
}
if (retval) {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
if (waitOnClose)
proc.waitFor();
}
} catch (Exception e) {
e.printStackTrace();
retval = false;
}
return retval;
}
{
boolean retval = false;
try {
String osName = System.getProperty("os.name");
String[] cmd = new String[3];
// Win9X
if (osName.equals(WIN_95) ||
osName.equals(WIN_98) ||
osName.startsWith(WIN_3X) ||
osName.startsWith(WIN_FW) ) {
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = batch_file;
retval = true;
}
// W2K or greater
else if ( osName.startsWith(WIN) ) {
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = batch_file;
retval = true;
}
if (retval) {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
if (waitOnClose)
proc.waitFor();
}
} catch (Exception e) {
e.printStackTrace();
retval = false;
}
return retval;
}
|
我试了, 可以啊!
加上这一段: 可以看执行的结果输出。
InputStream in = proc.getInputStream();
BufferedReader line = new BufferedReader(new InputStreamReader(in));
String l = line.readLine();
while (l!=null)
{
System.out.println(l);
l = line.readLine();
}
in.close();
加上这一段: 可以看执行的结果输出。
InputStream in = proc.getInputStream();
BufferedReader line = new BufferedReader(new InputStreamReader(in));
String l = line.readLine();
while (l!=null)
{
System.out.println(l);
l = line.readLine();
}
in.close();