java实现bat文件的创建和读取

2025-10-17 19:37:38

1、创建Test.java文件,将bat命令写入test.bat文件中

代码如下:

public static void creatBat(String command, String batURL) {    FileWriter fw=null;    try {        fw=new FileWriter(batURL);        fw.write(command);    } catch (IOException e) {        e.printStackTrace();        System.exit(0);    } finally {        if (fw != null) {            try {                fw.close();            } catch (IOException e) {                e.printStackTrace();                System.exit(0);            }        }    }}

java实现bat文件的创建和读取

2、在main函数中调用createBat方法,使用调用cmd的命令

Runtime.getRuntime().exec(cmd);实现调用,

代码如下:

public static void main(String[] args) throws IOException {    String batPath = "D:\\test.bat";    String cmd = "cmd /c start " + batPath;    try {        Process ps = Runtime.getRuntime().exec(cmd);        ps.waitFor();    } catch (IOException ioe) {        ioe.printStackTrace();    } catch (InterruptedException e) {        e.printStackTrace();    }}

java实现bat文件的创建和读取

3、如果想要在控制台输出dos窗口的内容,可以使用如下方法实现:

代码如下:

public static void run() {    try {        Process process = Runtime.getRuntime().exec("ipconfig");        InputStream in = process.getInputStream();        BufferedReader br = new BufferedReader(new InputStreamReader(in));        //StringBuffer b = new StringBuffer();        String line=null;        StringBuffer b=new StringBuffer();        while ((line=br.readLine())!=null) {            b.append(line+"\n");        }        System.out.println(b.toString());        process.waitFor();    } catch (Exception e) {        e.printStackTrace();    }}

java实现bat文件的创建和读取

4、最近在找的时将命令写入bat文件里面读取,后来发现应该可以直接调用dos里面的命令,来实现功能,这种的目前还没有尝试,如果有实现的方法,可以分享出来。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢