Java调用Bat

本文介绍了一个Java程序如何创建并调用Batch (bat) 文件的实例。该程序不仅生成了一个包含多个命令的bat文件,还展示了如何通过Java运行这个批处理文件,并捕获输出。此外,还提供了一个用于编译和运行Java程序的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Test3
{
	static final String path = "D:\\develop\\test.bat";

	public static void main(String[] args)
			throws IOException, InterruptedException
	{
		 printJava();
		createBat();
		Process p = null;
		File f = new File("d:");
		p = Runtime.getRuntime().exec(new String[] { "cmd", "/c", path },null,f);
		p.waitFor();
		System.out.print(p.exitValue());
		printf(p.getInputStream());
	}

	static void printf(InputStream out) throws IOException
	{
		String line = null;
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(out, "gbk"));
		while ((line = reader.readLine()) != null)
		{
			System.out.println(line);
		}
	}

	static void createBat() throws IOException
	{
		File file = new File(path);
		if (file.exists())
		{
			file.delete();
		}
		file.createNewFile();
		PrintWriter pw = new PrintWriter(file);
		pw.println("echo start");
		pw.println("pwd");
		pw.println("cd %JAVA_HOME%");
		pw.println("cd ..");
		pw.println("cd jre");
		pw.println("pwd");
		pw.println("ls");
		pw.println("javac Test.java");
		pw.println("clear");
		pw.println("for /L %%i in (0,1,2) do start java Test");
		pw.flush();
		pw.close();
	}
	
	static void printJava() throws IOException
	{
		String home = System.getProperty("java.home");
		System.out.print(home);
		File dir = new File(home);
		File file = new File(dir,"Test.java");
		if(file.exists())
			file.delete();
		file.createNewFile();
		PrintWriter pw = new PrintWriter(file);
		pw.println("public  class Test");
		pw.println("{");
			pw.println("public static void main(String[] args)");
			pw.println("{");
				 	pw.println("System.out.println(\"hello world\");");
				 	pw.println("int i = 0;");
				 	pw.println("while(i++ < 100000) System.out.println(\"hello world\");");
			 pw.println("}");
		pw.println("}");
		pw.flush();
		pw.close();
	}
}

  

posted on 2017-05-05 14:49 好吧,就是菜菜 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/shuiyonglewodezzzzz/p/6812968.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值