简体   繁体   English

Runtime.getRuntime()。exec如何运行goto命令

[英]Runtime.getRuntime().exec how to run goto commands

I'm trying to run small command-line code in java application to delete itself. 我正在尝试在Java应用程序中运行小的命令行代码以删除自身。 So the command would keep running and keeps trying to delete the file, and once the application is closed it would be deleted. 因此,该命令将继续运行并继续尝试删除该文件,并且一旦应用程序关闭,它将被删除。

I've tired passing the command into Runtime.getRuntime().exec but still unable to have it work. 我已经厌倦了将命令传递给Runtime.getRuntime()。exec,但仍然无法正常运行。

eg: 例如:

SET file="program.jar"
goto :d
:r
timeout /t 1
:d
del %file%
if exist %file% goto :r

Tried doing this which obviously looks wrong. 试图这样做,这显然看起来是错误的。 I've tired using ; 我累了; instead of && but doesn't work either. 而不是&&,但也不起作用。

Runtime.getRuntime().exec("cmd /c \"SET file=\"program.jar\" && goto :d && :r && timeout /t 1 && :d && del %file% && if exist %file% goto :r\"");

Works perfectly well in a .bat file but how do i implement it into java .exec() method. 在.bat文件中可以很好地工作,但是如何将其实现为java .exec()方法。 I could just run the .bat file but I would want all the code be contained inside java. 我可以只运行.bat文件,但我希望所有代码都包含在java中。

First, you can't use labels an goto s in a cmd one-liner. 首先,您不能在cmd单行代码中使用goto标签。 Use some kind of while TRUE loop instead. 请改用while TRUE循环。 In cmd terms: for /L %a in (1 0 2) do ... cmd表示: for /L %a in (1 0 2) do ...

Second, you need to apply Delayed Expansion . 其次,您需要应用延迟扩展 Proof: 证明:

==> SET "_file=init.ext"

==> SET "_file=prog.jar" & for /L %a in (1 1 2) do @echo %_file% %time% & timeout /T 3 1>NUL
init.ext  8:05:55,33
init.ext  8:05:55,33

==> set _file
_file=prog.jar

In above example, %_file% and %time% variables are expanded in parse time. 在上面的示例中, %_file%%time%变量在解析时进行了扩展。
On the other side, with delayed expansion enabled: !_file! 另一方面,启用了延迟扩展: !_file! and !time! !time! variables are expanded in execution time: 变量将在执行时间中扩展:

==> SET "_file=init.ext"

==> cmd /E /V /C SET "_file=prog.jar" ^& for /L %a in (1 1 2) do @echo !_file! !time! ^& timeout /T 3 1^>NUL
prog.jar  8:08:55,42
prog.jar  8:08:58,18

Hence, your one-liner could look as follows (verified from Windows cmd CLI for a locked file; loops until unlocked): 因此,单线代码可能如下所示(已从Windows cmd CLI验证是否有锁定的文件;直到解锁为止循环播放):

cmd /E /V /C SET "_file=program.jar" ^& for /L %a in (1 0 2) do if exist "!_file!" (del "!_file!" ^& timeout /T 2) else (exit /B)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM