java 生成bat_java 创建和执行bat

这是一个Java工具类,用于创建和执行批处理文件(BAT)。类中包含不同方法以在打开或不打开命令窗口的情况下执行BAT文件,并提供了创建BAT文件的方法,将指定的命令写入文件。
摘要由CSDN通过智能技术生成

/*

*/

package com.***app.mappcore.impl.util;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

/**

* 批处理文件的执行类.

* @author mapengfei

* @version 1.0.0 2015年10月26日

* @see

* @since JDK 1.5.0

*/

public class BATExecutorUtil {

/**

* java进程.

*/

public static Process process = null;

/**

* 开口窗口的模式执行bat文件.

* @param batFilePath bat文件的绝对路径

*/

public static void execBAT(final String batFilePath) {

if (process != null) {

process.destroy();

}

try {

process = Runtime.getRuntime().exec(COMMAND_K + batFilePath);

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 开口窗口的模式执行bat文件.

* @param batFilePath bat文件的绝对路径

*/

public static void execBATNoConsole(final String batFilePath) {

if (process != null) {

process.destroy();

}

try {

process = Runtime.getRuntime().exec(COMMAND_C + batFilePath);

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 执行命令

* @param command

*/

public static void  execCommand(final String command){

if (process != null) {

process.destroy();

}

try {

process = Runtime.getRuntime().exec(command);

} catch (IOException e) {

e.printStackTrace();

}

}

/*    public static boolean  execCommand(final String command){

try {

process = Runtime.getRuntime().exec(command);

process.waitFor();

process.destroy();

process = null;

} catch (Exception e) {

e.printStackTrace();

return false;

}

return true;

}*/

/**

* 将要执行的批处理命令写入到目标bat文件中

*

* @param command

* @param batFilePath

*/

public static void creatBAT(final String command, final String batFilePath) {

try {

File f = new File(batFilePath);

// 定义编码

OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "GBK");

BufferedWriter writer = new BufferedWriter(write);

writer.write(command);

writer.close();

write.close();

} catch (Exception e) {

System.out.println("写文件内容操作出错");

e.printStackTrace();

}

}

/**

* 打开命令窗口.

*/

public static final String COMMAND_K = "cmd /k start ";

/**

* 不打开命令窗口.

*/

public static final String COMMAND_C = "cmd /c ";

/**

* @param args

*/

public static void main(final String[] args) {

String batFilePath = "F:\\mapp\\installtemple\\test\\test.bat";

String content = "d:\ncd D:\\Program Files (x86)\\Inno Setup 5\n  Compil32 /cc  F:\\mapp\\installtemple\\test\\template.iss";

BATExecutorUtil.creatBAT(content, batFilePath);

BATExecutorUtil.execBATNoConsole(batFilePath);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值