使用Java运行Windows bat文件
在 2019年1月10日 上张贴 由 FlammulinaBlog发表回复阅读 4 次
在Java中运行一个简单的bat文件。
我们使用 ProcessBuilder这样运行Windows批处理文件:
ProcessBuilder processBuilder =
new ProcessBuilder("C:\\Users\\mkyong\\hello.bat");
//or
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd", "/c", "hello.bat");
File dir = new File("C:\\Users\\mkyong\\");
processBuilder.directory(dir);
或者, Runtime.getRuntime().exec像这样:
Process process = Runtime.getRuntime().exec(
"cmd /c hello.bat", null, new File("C:\\Users\\mkyong\\"));
Java示例
bat文件路径 C:\\Users\\mkyong\\hello.bat
@echo off
echo Hello World
Java示例读取上面的bat文件并显示输出。
JavaRunBatFile.java
package com.mkyong.concurrency;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaRunBatFile {
public static void main(String[] args) {
ProcessBuilder processBuilder = new ProcessBuilder("C:\\Users\\mkyong\\hello.bat");
//Process process = Runtime.getRuntime().exec(
// "cmd /c hello.bat", null, new File("C:\\Users\\mkyong\\"));
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(output);
System.exit(0);
} else {
//abnormal...
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出
Hello World
如果需要 Wifi.bat文件的小伙伴们请私信我