java实现bat文件的创建和读取
来源:网络收集 点击: 时间:2024-08-05创建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); } } }}

在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(); }}

如果想要在控制台输出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(); }}

最近在找的时将命令写入bat文件里面读取,后来发现应该可以直接调用dos里面的命令,来实现功能,这种的目前还没有尝试,如果有实现的方法,可以分享出来。
版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、文章链接:http://www.1haoku.cn/art_1065295.html