Java到批处理文件
但当我运行时,会出现这样的异常Java到批处理文件,java,batch-file,Java,Batch File,但当我运行时,会出现这样的异常 try { String comd ="E:/ior1.txt"; Runtime rt = Runtime.getRuntime(); rt.exec("C:/tes1.bat"+comd+""); System.out.println("Process exitValue: "); } catch (Exception e) { System.out.println("Unexpected excepti
try {
String comd ="E:/ior1.txt";
Runtime rt = Runtime.getRuntime();
rt.exec("C:/tes1.bat"+comd+"");
System.out.println("Process exitValue: ");
}
catch (Exception e)
{
System.out.println("Unexpected exception Trying to Execute Job: " +e);
}
这是批处理文件内容
Unexpected exception Trying to Execute Job: java.io.IOException: CreateProcess:
C:/tes1.batE:/ior1.txt error=2
Press any key to continue . . .
.bat之后(rt.exec行中)缺少一个空格
编辑: 您还可以尝试执行:
echo "testing"
echo %1
当我认为这是正确的,你必须在bat命令和参数之间加一个空格 编辑: 编辑2: 再次查看并在我的电脑上测试后,其他答案似乎正确。cmd不见了
try {
String comd ="E:/ior1.txt";
Runtime rt = Runtime.getRuntime();
rt.exec("C:/tes1.bat "+comd+"");
System.out.println("Process exitValue: ");
}
catch (Exception e)
{
System.out.println("Unexpected exception Trying to Execute Job: " +e);
}
尝试在exec调用前加上
cmd/c
或call
,例如
rt.exec("cmd /c c:/tes1.bat "+comd);
(我现在没有可用的Windows box,因此无法测试,但据我记忆所及,启动批处理文件需要先启动命令解释器。)laalto评论的补充内容: Runntime提供了exec()的多个签名
请注意,如果您必须在生产环境中使用外部流程,那么在Java程序中执行外部流程会有很多问题 例如,您必须意识到这样一个事实,即如果进程的输出大于JVMOS使用的缓冲区,exec将永远阻塞 我通常使用带有线程的包装器来读取缓冲区 它并不完美,但类似(有关用法的详细信息,请参见main()):
/**
*在给定环境中的给定目录中执行给定的依赖于操作系统的命令。
*参数在构造时给定,并且初始化的对象是不可变的。
*在对象初始化和执行blocking exec()方法之后,状态
*不能改变。执行的结果可以通过get方法访问
*用于exitValue、stdOut和stdErr属性。在exec()方法完成之前
*executed属性为false,其他getter的结果未定义(null)。
*/
公共类命令执行器{
/**
*指定终止进程的次数
*如果操作系统出现中断,则等待
*/
公共静态最终整数运行次数=2;
/**
*用于测试和作为使用示例。
*/
公共静态void main(字符串[]args){
System.out.println(“CommandExecutor.main测试开始”);
字符串命令\u 01=“cmd.exe/C dir”;
文件目录01=新文件(“C:\\”;
System.out.println(“CommandExecutor.main Testing.Input:”);
System.out.println(“CommandExecutor.main Testing.command:”+command_01);
System.out.println(“CommandExecutor.main Testing.dir:+dir_01”);
CommandExecutor ce_01=新的CommandExecutor(command_01,null,dir_01);
ce_01.exec();
System.out.println(“CommandExecutor.main Testing.Output:”);
System.out.println(“exitValue:+ce_01.getExitValue());
System.out.println(“stdout:+ce_01.getStdout());
System.out.println(“stderr:+ce_01.getStderr());
字符串命令_02=“cmd.exe/C dirs”;
文件目录02=新文件(“C:\\”;
System.out.println(“CommandExecutor.main Testing.Input:”);
System.out.println(“CommandExecutor.main Testing.command:”+command_02);
System.out.println(“CommandExecutor.main Testing.dir:+dir_02”);
CommandExecutor ce_02=新的CommandExecutor(command_02,null,dir_02);
ce_02.exec();
System.out.println(“CommandExecutor.main Testing.Output:”);
System.out.println(“exitValue:+ce_02.getExitValue());
System.out.println(“stdout:+ce_02.getStdout());
System.out.println(“stderr:+ce_02.getStderr());
System.out.println(“CommandExecutor.main测试端”);
}
/*
*要执行的命令
*/
保护字符串命令;
/*
*用于执行命令的环境
*/
受保护字符串[]env;
/*
*要在其中执行命令的目录
*/
受保护文件目录;
/*
*执行命令时设置的标志
*/
受保护的布尔值=false;
/*
*从操作系统退出值
*/
受保护的内在价值;
/*
*派生的操作系统进程的句柄
*/
保护过程;
/*
*标准差
*/
受保护列表标准;
/*
*用于清空stderr缓冲区的工作线程
*/
受保护的线程标准读取器;
/*
*标准输出
*/
受保护列表标准输出;
/*
*用于清空标准输出缓冲区的工作线程
*/
保护螺纹螺纹螺纹;
/**
*创建初始化为执行命令的CommandExecutor的新实例
*在具有指定环境的单独进程中指定的命令
*和工作目录。
*
*@param-env
*/
公共命令执行器(字符串命令,字符串[]环境,文件目录){
this.command=命令;
this.env=env;
this.dir=dir;
}
/**
*为stderr创建读取器线程
*/
受保护的void connectstderreader(){
stderr=newarraylist();
final InputStream=process.getErrorStream();
最终缓冲读取器=
新的BufferedReader(新的InputStreamReader(stream));
stderReader=new线程(new Runnable(){
公开募捐{
字符串nextLine=null;
试一试{
而((nextLine=reader.readLine())!=null){
标准添加(下一行);
}
}捕获(IOE异常){
System.out.println(
“读卡器线程中的CommandExecutor.ConnectStderReader()错误”);
e、 printStackTrace(系统输出);
}
}
});
stderReader.start();
}
/**
*为标准输出创建读取器线程
*/
受保护的void connectstdoutrader(){
stdout=newarraylist();
final InputStream=process.getInputStream();
最终缓冲读取器=
新的BufferedReader(新的InputStreamReader(stream));
stdoutrader=new线程(new Runnable()){
公开募捐{
字符串nextLine=null;
试一试{
而((nextLine=reader.readLine())!=null){
标准添加(下一行);
}
}捕获(IOE异常){
System.out.println(
“读卡器线程中的CommandExecutor.ConnectstDoutrader()错误”);
rt.exec("cmd /c c:/tes1.bat "+comd);
rt.exec("cmd /c c:/tes1.bat "+comd);
rt.exec("cmd /c c:/tes1.bat "+comd);
rt.exec(new String[] {"cmd","/c","c:/tes1.bat",comd});
/**
* Executes a given OS dependent command in a given directory with a given environment.
* The parameters are given at construction time and the initialized object is immutable.
* After the object initialization and execution of the blocking exec() method the state
* can't be changed. The result of the execution can be accessed through the get methods
* for the exitValue, stdOut, and stdErr properties. Before the exec() method is completed
* the excuted property is false and the result of other getters is undefined (null).
*/
public class CommandExecutor {
/**
* Specifies the number of times the termination of the process is
* waited for if the OS gives interruptions
*/
public static final int NUMBER_OF_RUNS = 2;
/**
* Used for testing and as example of usage.
*/
public static void main(String[] args) {
System.out.println("CommandExecutor.main Testing Begin");
String command_01 = "cmd.exe /C dir";
File dir_01 = new File("C:\\");
System.out.println("CommandExecutor.main Testing. Input: ");
System.out.println("CommandExecutor.main Testing. command: " + command_01);
System.out.println("CommandExecutor.main Testing. dir: " + dir_01);
CommandExecutor ce_01 = new CommandExecutor(command_01, null, dir_01);
ce_01.exec();
System.out.println("CommandExecutor.main Testing. Output:");
System.out.println(" exitValue: " + ce_01.getExitValue());
System.out.println(" stdout: " + ce_01.getStdout());
System.out.println(" stderr: " + ce_01.getStderr());
String command_02 = "cmd.exe /C dirs";
File dir_02 = new File("C:\\");
System.out.println("CommandExecutor.main Testing. Input: ");
System.out.println("CommandExecutor.main Testing. command: " + command_02);
System.out.println("CommandExecutor.main Testing. dir: " + dir_02);
CommandExecutor ce_02 = new CommandExecutor(command_02, null, dir_02);
ce_02.exec();
System.out.println("CommandExecutor.main Testing. Output:");
System.out.println(" exitValue: " + ce_02.getExitValue());
System.out.println(" stdout: " + ce_02.getStdout());
System.out.println(" stderr: " + ce_02.getStderr());
System.out.println("CommandExecutor.main Testing End");
}
/*
* The command to execute
*/
protected String command;
/*
* The environment to execute the command with
*/
protected String[] env;
/*
* The directory to execute the command in
*/
protected File dir;
/*
* Flag set when the command has been executed
*/
protected boolean executed = false;
/*
* Exit value from the OS
*/
protected int exitValue;
/*
* Handle to the spawned OS process
*/
protected Process process;
/*
* Std error
*/
protected List<String> stderr;
/*
* Worker Thread to empty the stderr buffer
*/
protected Thread stderrReader;
/*
* Std output
*/
protected List<String> stdout;
/*
* Worker Thread to empty the stdout buffer
*/
protected Thread stdoutReader;
/**
* Creates a new instance of the CommandExecutor initialized to execute the
* specified command in a separate process with the specified environment
* and working directory.
*
* @param env
*/
public CommandExecutor(String command, String[] env, File dir) {
this.command = command;
this.env = env;
this.dir = dir;
}
/**
* Creates a reader thread for the stderr
*/
protected void connectStderrReader() {
stderr = new ArrayList<String>();
final InputStream stream = process.getErrorStream();
final BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
stderrReader = new Thread(new Runnable() {
public void run() {
String nextLine = null;
try {
while ((nextLine = reader.readLine()) != null) {
stderr.add(nextLine);
}
} catch (IOException e) {
System.out.println(
"CommandExecutor.connectStderrReader() error in reader thread");
e.printStackTrace(System.out);
}
}
});
stderrReader.start();
}
/**
* Creates a reader thread for the stdout
*/
protected void connectStdoutReader() {
stdout = new ArrayList<String>();
final InputStream stream = process.getInputStream();
final BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
stdoutReader = new Thread(new Runnable() {
public void run() {
String nextLine = null;
try {
while ((nextLine = reader.readLine()) != null) {
stdout.add(nextLine);
}
} catch (IOException e) {
System.out.println(
"CommandExecutor.connectStdoutReader() error in reader thread");
e.printStackTrace(System.out);
}
}
});
stdoutReader.start();
}
/**
* Creates the process for the command
*/
protected void createProcess() {
try {
process = Runtime.getRuntime().exec(command, env, dir);
} catch (IOException e) {
System.out.println("CommandExecutor.exec() error in process creation. Exception: " + e);
e.printStackTrace(System.out);
}
}
/**
* Executes command in a separate process in the specified directory. Method will block until
* the process has terminated. Command will only be executed once.
*/
public synchronized void exec() {
// Future enhancement: check for interrupts to make the blocking nature interruptible.
if (!executed) {
createProcess();
connectStdoutReader();
connectStderrReader();
waitForProcess();
joinThreads();
exitValue = process.exitValue();
executed = true;
}
}
/**
* @return the command
*/
public String getCommand() {
return command;
}
/**
* @return the dir
*/
public File getDir() {
return dir;
}
/**
* @return the env
*/
public String[] getEnv() {
return env;
}
/**
* @return the exitValue
*/
public int getExitValue() {
return exitValue;
}
/**
* @return the stderr
*/
public List<String> getStderr() {
return stderr;
}
/**
* @return the stdout
*/
public List<String> getStdout() {
return stdout;
}
/**
* @return the executed
*/
public boolean isExecuted() {
return executed;
}
/**
* Joins on the 2 Reader Thread to empty the buffers
*/
protected void joinThreads() {
try {
stderrReader.join();
stdoutReader.join();
} catch (InterruptedException e) {
System.out.println("CommandExecutor.joinThreads() error. Exception: ");
e.printStackTrace(System.out);
}
}
/**
* Creates a String representing the state of the object
*/
@Override
public synchronized String toString() {
StringBuilder result = new StringBuilder();
result.append("CommandExecutor:");
result.append(" command: " + command);
result.append(" env: " + Arrays.deepToString(env));
result.append(" dir: " + dir);
result.append(" executed: " + executed);
result.append(" exitValue: " + exitValue);
result.append(" stdout: " + stdout);
result.append(" stderr: " + stderr);
return result.toString();
}
/**
* Waits for the process to terminate
*/
protected void waitForProcess() {
int numberOfRuns = 0;
boolean terminated = false;
while ((!terminated) && (numberOfRuns < NUMBER_OF_RUNS)) {
try {
process.waitFor();
terminated = true;
} catch (InterruptedException e) {
System.out.println("CommandExecutor.waitForProcess() error");
e.printStackTrace(System.out);
numberOfRuns++;
}
}
}
}