手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

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

时间:2024-10-14 10:18:20

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里面的命令,来实现功能,这种的目前还没有尝试,如果有实现的方法,可以分享出来。

© 手抄报圈