如何在Java应用程序中检测运行JVM的终端。

huangapple go评论71阅读模式
英文:

how to detect the terminal running the JVM within the java Application

问题

我正在创建一个小的CLI Java应用程序。
在Windows上,我遇到了一些问题,以便在不同终端上实现一致的清屏功能。
我找到的所有解决方案都是基于检测操作系统来实现的。
类似于:
System.getProperty("os.name").indexOf("win") >= 0
并根据是否为Windows应用不同的已记录的https://stackoverflow.com/questions/2979383/java-clear-the-console答案。

这种方法的缺点是,如果你在cmd、git-bash或Cygwin终端中运行Java应用程序,清屏的效果并不相同。你不能在git-bash中使用cmd的清屏命令,反之亦然。

基于这一点,我更希望能够检测我所在的终端。
我想通过尝试运行一个特定于Linux的命令,然后使用ProcessBuilder来检测是否失败,以此来判断我是否在cmd终端中。但是我能想到的所有命令在cmd终端中也都存在:ls、grep、awk。这可能是因为我安装了WSL(Windows Linux Subsystem),但我不确定。

有没有办法检测正在运行JVM的终端?

英文:

I am creating a little CLI java application.
I have some trouble to manage a consistent clear screen functionality on Windows.
All solutions I have found are based on detecting the operating system.
Something like:
System.getProperty("os.name").indexOf("win") >= 0
and apply one of the documented https://stackoverflow.com/questions/2979383/java-clear-the-console answer depending whether it is Windows or not.

The disadvantage of this approach is that the clear screen is not working the same way if you run your java application in a cmd, git-bash or a Cygwin terminal. You cannot apply the cmd clear screen inside git-bash and the other way arround.

Based on that I would prefer to detect the terminal I am running on.
I thought to check if a Linux specific command would fail using a ProcessBuilder as a way to detect that I am in a cmd terminal but all the one I could think of also exists in a cmd terminals: ls, grep, awk. It is maybe because I have a WSL (Windows Linux Subsystem) installed but I am not sure.

Is there a way to detect the terminal running the JVM?

答案1

得分: 0

一个简单的方法是检查系统进程的环境变量。您可以通过ProcessBuilder来实现这一点,方法是检查是否定义了PS1环境变量。

我找到的这个变量可能并不是完全健壮的,而且可能在Windows环境中存在。在那种情况下,您可以在ProcessBuilder.environment()返回的集合中找到另一个变量。

ProcessBuilder pb = new ProcessBuilder();
if(pb.environment().containsKey("PS1")) {
  System.out.println("非Windows控制台");
} else {
  System.out.println("Windows控制台");
}
英文:

A simple way to achieve this is to introspect the environment variables of a system process.
You can achieve this with ProcessBuilder by checking if the PS1 environment variable is defined.

This is the variable I found, it is maybe not completely robust and could be present in your Windows environment. In that case find an other one in the collection returned by ProcessBuilder.environment().

  ProcessBuilder pb = new ProcessBuilder();
  if(pb.environment().containsKey("PS1")) {
    System.out.println("non Windows console");
  } else {
    System.out.println("Windows console");
  }

huangapple
  • 本文由 发表于 2020年5月31日 05:15:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/62108747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定