1

这就是我想要实现的目标:从 JAVA 程序运行批处理文件。批处理在特定文件夹中创建一个新文件,假设文件夹“A”。创建新文件后,JAVA 程序将新创建的文件从文件夹“A”移动到文件夹“B”。

以下是代码片段:

// Run a batch that creates a file
String[] cmd = new String[]{"cmd", "/C", "start /min" + batchFilePath + batchFileName};
Process proc = Runtime.getRuntime().exec(cmd);  
proc.waitFor();


// Command in the batch file

dir c:\ > C:\Chen_Med\EDICron\EDIOUT\test.edi
exit

// Move the file created by batch
boolean result2= ediOutFile.renameTo(new File(processedFolder, ediOutFile.getName()));

这就是我运行上述代码时发生的情况:在文件夹“A”中创建了新文件。但是,新创建的文件不会移动到文件夹“B”。

分析:

上面的代码没有语法问题。我尝试了移动文件的替代方法。也就是说,将文件夹“A”中的文件读写到文件夹“B”,然后从文件夹“A”中删除文件。新文件在文件夹“B”中创建,但是文件并未从文件夹“B”中删除。当我运行另一个试图移动文件的程序时,在执行上述程序后,它就可以工作了。也就是说,运行时控制文件似乎存在问题。

请帮我解决问题。我浪费了一整天的时间试图找出解决方案:(

4

1 回答 1

3

By using cmd /c start ... to start the batch file, you're starting it asynchronously -- i.e., cmd.exe is creating a second process to run the batch file, and the proc.waitFor() is waiting for the original cmd.exe, but not for the batch file itself. The batch file is then running in parallel with the Java program, and the attempt to rename the file from Java occurs before the file is even created.

Instead, just use cmd /c batch.bat, and this should work fine.

于 2012-05-04T14:09:47.457 回答