要在Java中调用.bat文件并获取结果,可以使用Java中的Runtime类的exec()方法。以下是一个示例代码:
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class CallBatFile {public static void main(String[] args) {try {// 调用命令行执行.bat文件Process process = Runtime.getRuntime().exec("cmd /c myscript.bat");// 获取.bat文件执行的输出流InputStream inputStream = process.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));// 读取输出流中的内容String line;while ((line = reader.readLine()) != null) {System.out.println(line);}// 等待.bat文件执行完毕int exitCode = process.waitFor();System.out.println("Exit Code: " + exitCode);} catch (IOException | InterruptedException e) {e.printStackTrace();}}}在上述代码中,我们通过调用Runtime的exec()方法来执行.bat文件。使用"cmd /c"来执行命令行,然后指定.bat文件的路径。然后通过获取.bat文件的输出流,我们可以读取.bat文件执行的结果。最后,通过调用waitFor()方法等待.bat文件执行完毕,获取执行的退出码。
请注意,这个例子假设.bat文件是在当前工作目录下的,如果.bat文件的路径不在当前工作目录,需要提供完整的路径。

