0

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 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?

Antoine Wils
  • 349
  • 2
  • 4
  • 21

1 Answers1

0

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");
  }
Antoine Wils
  • 349
  • 2
  • 4
  • 21