2000年3月13日星期一

Java生成并调用.bat 文件

package battest;

import java.io.File;
import java.io.FileOutputStream;

public class OPBat {
//文件分隔符。
public String fileSapter = java.io.File.separator;

public void testBat() {
//当前工程路径。
String proRootPath = System.getProperty("user.dir");
String batFilePath = proRootPath + java.io.File.separator + "test.bat";

//如果test.bat文件存在则将其删除。
File batFile = new File(batFilePath);
if (batFile.exists()) {
batFile.delete();
}
//生成 test.bat 文件。
try {
batFile.createNewFile();
FileOutputStream fos = new FileOutputStream(batFile);

String proSysPath = proRootPath.substring(0, 2);
//组织test.bat 文件内容。
String strInput = proSysPath + " n" + "cd " + " "" + proRootPath +
fileSapter + " "" +
" n" + "start exeTest.exe" + " n" + "exit";

System.out.println("test.bat内容是: n" + strInput);

byte[] byt = strInput.getBytes();
fos.write(byt);
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
System.out.println("test.bat 路径是:" + batFilePath);
//调用并执行test.bat文件。
try {
Runtime.getRuntime().exec(batFilePath);
} catch (Exception ex) {
ex.printStackTrace();
return;
}
}

//主函数。
public static void main(String[] args) {
OPBat opbat = new OPBat();
opbat.testBat();
}
}

没有评论:

发表评论