运行时如何使Java程序反复启动
我希望这个程序不断地启动新的实例。这个程序没有真正的功能,我只是好奇。我能够让它找到自己的文件路径,但当我使用运行时类并使用该文件路径执行它时,什么都没有发生。我也尝试过使用ProcessBuilder,但还是什么都没发生。我确保将它构建到一个jar中并执行它,因为我知道如果在编辑器中运行它,它将无法工作
public class Main
{
public static void main(String[] args) throws Exception
{
System.out.println("Started");
CodeSource codeSource = Main.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
System.out.println("File: " + jarFile.toURI().toString());
Runtime.getRuntime().exec(("java -jar "+jarFile.toURI().toString()));
}
}
# 1 楼答案
我不确定这是否会帮助您,但这是另一种简单的技术,我的java类会重复执行自己,除非您选择主菜单上的退出选项,或者输入错误的输入
这里,如果你看到代码,我做的是一个基本的区域查找程序,使用Switch case语句创建可执行的选择选项
从
System.out.println()
开始,我在那里打印了正方形、圆形、三角形等选项,我创建了一个无限for循环,如下面代码中所示 无限for循环括号在主开关case语句括号之后结束。因为如果你注意到有两个switch case语句。一个是主要选项,另一个是“你想继续吗?”这就是我给出的另外两个选项。如果用户点击1,for循环将继续,如果用户点击0,System.exit(0);
将被执行,这将终止无限循环,导致整个代码终止