Creating a “.bat” file, run it and delete it from Java

僤鯓⒐⒋嵵緔 提交于 2020-01-26 00:40:12

问题


I'm making a .bat dynamically in Java.

After creating the file and exectuing it, I want to delete it.

In order to make sure that delete() will be executing after running the .bat file, I delete the file within a different thread.

Is this a good approach for this task? How would you implement it in a better way?

final File file = new File("run.bat");
file.createNewFile();
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(COMMAND1);
writer.println(COMMAND2);

.... ANOTHER COMMANDS

writer.close();
Runtime.getRuntime().exec("cmd /c start a.bat");

new Thread(new Runnable() {
    public void run() {
        file.delete();
    }
}).run();

回答1:


I wouldnt delete the file in a different thread, what if the file execution is still running at the time you try to delete it?

I would consider asking the exit code from the file, or use a process.waitFor() which causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Process p = Runtime.getRuntime().exec("cmd /c start a.bat");
p.waitFor();
file.delete();



回答2:


Try this which causes the code to wait until the batch file execution is complete before deleting the file.

Process batchFileExecutionProcess = Runtime.getRuntime().exec("cmd /c start a.bat");
batchFileExecutionProcess.waitFor();
file.delete();

Ideally, you would build error handling into this solution as well, such as looking for a 0 return from the waitFor() method.




回答3:


No, it's not good approach. Actually I don't see any advantage of the extra thread. Most likely it will attempt to delete the file while it's still being used by cmd and deletion will fail. Instead you should use Process object (the result of exec()) and wait until the it finished and delete the file then:

Process p = Runtime.getRuntime().exec("cmd /c start a.bat");
p.waitFor();
file.delete()


来源:https://stackoverflow.com/questions/15137006/creating-a-bat-file-run-it-and-delete-it-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!