创建一个".bat"文件,运行它并从Java中删除它 [英] Creating a ".bat" file, run it and delete it from Java

查看:122
本文介绍了创建一个".bat"文件,运行它并从Java中删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Java中动态制作一个.bat.

I'm making a .bat dynamically in Java.

创建文件并执行后,我要删除它.

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

为了确保在运行.bat文件后将执行delete(),我在另一个线程中删除了该文件.

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();

推荐答案

我不会在其他线程中删除文件,如果在尝试删除该文件时仍在运行该文件,该怎么办?

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?

我会考虑从文件中询问退出代码,或使用process.waitFor( ),导致当前线程在必要时等待,直到此Process对象表示的进程终止.

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();

这篇关于创建一个".bat"文件,运行它并从Java中删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆