gpt4 book ai didi

java - 自定义卸载程序无法在 Java 中自毁

转载 作者:行者123 更新时间:2023-11-30 05:35:59 25 4
gpt4 key购买 nike

我正在尝试使用 Java 制作自定义卸载程序,我可以使用 Launch4J 将其转换为控制台应用程序。我想要实现的是卸载程序完成后,它需要打开命令提示符将其删除,然后删除安装文件夹。但是,我只收到此错误:该进程无法访问该文件,因为它正在被另一个进程使用
process
,但是我可以看到卸载程序已经被删除,但是安装目录还没有。难道卸载程序仍然在内存中打开,或者我可以做什么来解决这个问题?


public static void main(String[] args) {
String command;
command = "\"";
command += "echo Self Destruction Commenced.";
command += "& del /f /q \"" + System.getProperty("user.dir") + "\\uninstaller.exe\"";
command += "& rmdir /q /s \"" + System.getProperty("user.dir") + "\"";
command += "& echo. & echo MyProgram successfully uninstalled...";
command += "& set /p exitkey= \"Press [ENTER] key to finish...\" ";
command += "\"";
selfDestructProgram("start cmd.exe /c " + command);
}

private static void selfDestructProgram(String command) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd.exe", "/c", command);
try {
Process process = processBuilder.start();
process.waitFor();
} catch (Exception var3) {
var3.printStackTrace();
}
}

最佳答案

安装目录是新cmd中仍然打开的进程。你需要做的就是使用新打开的cmd cd 到安装目录的父目录,然后就可以删除它了。请改用下面的代码:

public static void main(String[] args) {
//get the path to the parent directory
File workingDir = new File(System.getProperty("user.dir"));
String parentDir = workingDir.getParent();

String command;
command = "\"";
command += "echo Self Destruction Commenced.";
command += "& del /f /q \"" + System.getProperty("user.dir") + "\\uninstaller.exe\"";
command += "& rmdir /q /s \"" + System.getProperty("user.dir") + "\"";
command += "& echo. & echo MyProgram successfully uninstalled...";
command += "& set /p exitkey= \"Press [ENTER] key to finish...\" ";
command += "\"";

//first cd to this parent directory before deleting the child directory, which is the installtion directory.
selfDestructProgram("cd /d " + parentDir + " & start cmd.exe /c " + command);
}

private static void selfDestructProgram(String command) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd.exe", "/c", command);
try {
Process process = processBuilder.start();
process.waitFor();
} catch (Exception var3) {
var3.printStackTrace();
}
}

目前无法删除安装目录,因为它在cmd中打开,导致其被锁定,无法进行删除或重命名或其他一些文件操作。

关于java - 自定义卸载程序无法在 Java 中自毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com