標籤:java 建立和執行bat
/*
*/
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;
/**
* 批次檔的執行類.<br>
* @author mapengfei <br>
* @version 1.0.0 2015年10月26日<br>
* @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);
}
}
java 建立和執行bat