问题描述
我想在 linux 中使用终端执行命令.现在为了做到这一点,我不能像 Windows 那样对 cmd 进行硬编码.如何以编程方式从 java 中获取终端名称作为字符串?
I want to execute a command with the terminal in linux. Now in order to do this I can't hard code cmd like I do windows. How do I get the terminal name programatically as String from java?
new ProcessBuilder(new String[] {"xfce4-terminal", "--title="+windowTitle, "--hold", "-x", "java", "-jar", decodedPath, "run"}).start();
注意字符串xfce4-terminal".这取决于他们拥有的 Linux 发行版.有什么可靠的方法可以获取 java 命令的终端 exe.在我看来,它应该由 System.getProperty(os.terminal") 实现,但是,它不存在.
Notice the string "xfce4-terminal". This changes depending on what distribution of linux they have. What reliable way is there to get the terminal exe for java commands. In my opinion it should by System.getProperty("os.terminal") but, that doesn't exist.
推荐答案
这里有一个跨平台的方式来确定 os 终端.支持windows、mac和linux
here is a cross platform way to determine the os terminal. supports windows, mac and linux
public static String osName = System.getProperty("os.name");
public static String[] windows_terminals = new String[]
{
"cmd",
"powershell",//seems to freak out and seems to be beta even in 2020 with all it's bugs
};
public static String[] mac_terminals = new String[]
{
"bin/bash"
};
public static String[] linux_terminals = new String[]
{
"/usr/bin/gcm-calibrate",
"/usr/bin/gnome-terminal",
"/usr/bin/mosh-client",
"/usr/bin/mosh-server",
"/usr/bin/mrxvt",
"/usr/bin/mrxvt-full",
"/usr/bin/roxterm",
"/usr/bin/rxvt-unicode",
"/usr/bin/urxvt",
"/usr/bin/urxvtd",
"/usr/bin/vinagre",
"/usr/bin/x-terminal-emulator",
"/usr/bin/xfce4-terminal",
"/usr/bin/xterm",
"/usr/bin/aterm",
"/usr/bin/guake",
"/usr/bin/Kuake",
"/usr/bin/rxvt",
"/usr/bin/rxvt-unicode",
"/usr/bin/Terminator",
"/usr/bin/Terminology",
"/usr/bin/tilda",
"/usr/bin/wterm",
"/usr/bin/Yakuake",
"/usr/bin/Eterm",
"/usr/bin/gnome-terminal.wrapper",
"/usr/bin/koi8rxterm",
"/usr/bin/konsole",
"/usr/bin/lxterm",
"/usr/bin/mlterm",
"/usr/bin/mrxvt-full",
"/usr/bin/roxterm",
"/usr/bin/rxvt-xpm",
"/usr/bin/rxvt-xterm",
"/usr/bin/urxvt",
"/usr/bin/uxterm",
"/usr/bin/xfce4-terminal.wrapper",
"/usr/bin/xterm",
"/usr/bin/xvt"
};
public static String getTerminal()
{
String[] cmds = getTerminals(osName);
for(String cmd : cmds)
{
try
{
Runtime.getRuntime().exec(cmd + " cd " + System.getProperty("user.dir"));
return cmd;
}
catch (Throwable e) {}
}
return null;
}
public static String[] getTerminals(String os)
{
return os.contains("windows") ? windows_terminals : os.contains("mac") ? mac_terminals : os.contains("linux") ? linux_terminals : null;
}
这篇关于如何获取linux终端名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!