loading...

Is there a way to make the computer's native console (if there is one) appear in Java?

calin92540842 profile image PDS OWNER CALIN (Calin Baenen) ・1 min read

So, I a program in Java that uses the console, currently I use this setup:

Java

// Two snippets of the program
Console c = System.console();
// Some code
c.readLine();

Console

javac program.java
java program

but instead of doing that, is there any way I can compile the class file(s) into a .jar file while keeping the console there? My goal is to open the console without having to use the console to navigate to the app, then inputting the second line of the given example.
So, is there any way to do this?

Thanks!
Cheers!

Discussion

markdown guide
 

What you can do is create a runnable JAR file. For that, you need to include a file MANIFEST.MF in the META-INF subfolder of you JAR file. IDEs like Eclipse or IntelliJ support you in doing that.

That manifest needs to reference the main class name. It may look similar to this:

Manifest-Version: 1.0
Main-Class: programpkg.Program
Class-Path: .

Here's what my example Java class looks like. It looks a bit different than yours, but it reads a line from the console:

package programpkg;

import java.util.Scanner;

public class Program {

  public static void main(String[] args) {
    try (Scanner sc = new Scanner(System.in);) {
      System.out.print("Please enter a line: ");
      String line = sc.nextLine();
      System.out.println(line);
    }
  }
}

Depending on the operating system and JRE, you may be able to double click on the JAR file to start it.
In Windows 10, and if you use OpenJDK, one way to start it is creating a batch script start.bat like with these contents, place it in the same folder as your jar:

java -jar Program.jar
pause

and then start it with double click

 

I heard manifest.txt works too? Is this true? Thanks again for your help!

 

Sorry, there was a typo in my original comment that I corrected now. The correct name in the JAR file is MANIFEST.MF.

I guess what you are referring to is that you can specify a MANIFEST.txt as input to the jar tool, as documented in the Oracle docs. That's correct. But I think that inside the JAR file itself, the file name must be MANIFEST.MF.

 

From what I understand you wan't to open a console at the given folder you're at? On windows you can hold Shift and right click inside a Windows folder, that will give you more options. For example Windows powershell, or in my case when having a WSL (Linux sub system) I also have the option to open a Ubuntu 18.04 LTS terminal at the given folder.

image

If this isn't what you wanted, than that's my bad. But this is a need trick anyways.
And most applications like Visual Studio Code/Intellij always open a terminal at the root folder.

 

This is a neat trick, but I was looking for a bit of Java code to open the system's local console. Maybe something around the lines of:

System.console().open();

?