java—如何使用process builder使用本机gui执行命令

9jyewag0  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(339)
if(os.contains("windows"))
            {
                File bat = new File(System.getenv("APPDATA") + "/SelfCommandPrompt", appId + "-run.bat");
                bat.getParentFile().mkdirs();
                List<String> list = new ArrayList(1);
                list.add("@echo off");
                list.add("start" + " \"" + appName + "\" " + command);
                IOUtils.saveFileLines(list, bat, true);
                ProcessBuilder pb = new ProcessBuilder(bat.getAbsolutePath());
                //inherit IO and main directory
                pb.directory(getProgramDir());
                //fire the batch file
                pb.start();
                System.exit(0);
            }

所以我动态地创建了一个.bat文件,我想运行这个过程,但不是在后台。java强制进程在后台发生,我如何使它不在后台发生?我不想从.bat文件中获取输出流,我只想用双击时使用的本机gui执行它。我在这些论坛上看到的每一个地方,它都只告诉我如何在后台进行,并获得输出流?为什么在process builder中没有布尔值?对于我的程序,我想用双击命令提示符终端重新启动我的java程序。我测试了.bat文件,但java再次强制它在后台执行。
另一个不在后台执行进程的用法。一个游戏的java启动程序,它使用gui执行一个程序,而不是在我将来可能需要的后台。
还有基于环境动态生成的bat文件输出

java -Dfile.encoding=Cp1252 -cp C:\Users\jredfox\Documents\MDK\md5-spreadsheet\filededuper\bin;C:\Users\jredfox\Documents\MDK\md5-spreadsheet\filededuper\libs\apache-codecs.jar jredfox.selfcmd.SelfCommandPrompt true jredfox.filededuper.Main

编辑我想出了一个windows命令,但是,只有windows。我需要mac的命令

Runtime.getRuntime().exec("cmd /c start" + " \"" + appName + "\" " + command);
kdfy810k

kdfy810k1#

我想出来了。
基本上,在linux上获取终端字符串需要为其创建api
在appdata中保存所需的shell脚本
制作api以获取应用程序数据文件夹
创建自定义命令
如果条件不符合,则返回 System.console != null 因为我的东西和你的不一样。
在新终端窗口中执行命令,因此使用操作系统命令创建新的本机终端。
所有的代码都在这里。https://github.com/jredfox/selfcommandprompt/blob/main/src/jredfox/selfcmd/selfcommandprompt.java#l236

sg2wtvxw

sg2wtvxw2#

若要使启动程序可移植到其他操作系统,请不要为该命令生成windows批处理文件。如果jar的路径在本地变量pathtothejar中,您可以尝试使用args确定当前java home/vm的启动命令:

String java = Path.of(System.getProperty("java.home"),"bin", "java").toAbsolutePath().toString();
String cmdToLaunch = java + " -jar "+pathToTheJar;

在windows上,“cmd”是shell/interpreter的命令,控制台窗口由conhost.exe提供。要使批处理命令在“cmd”下的新窗口中打开,可以运行:

String [] console = new String[] {"conhost.exe"};
// Console closes after bat ends:
String cmdToLaunch = bat.getAbsolutePath() + " & exit";
ProcessBuilder pb = new ProcessBuilder(console);
pb.start();
try(OutputStream os = p.getOutputStream()) {
    os.write(cmdToLaunch.getBytes());
    os.write(System.lineSeparator().getBytes());
}

最后的“出口”关闭窗口。如果希望窗口保持打开状态或在出现错误后保持打开状态,请使用以下选项之一:

// Console stays open:
String cmdToLaunch = bat.getAbsolutePath();
// Console open if bat returns OK status:
String cmdToLaunch = bat.getAbsolutePath() + " && exit";

相关问题