Как открыть терминал java

Как мне сделать, чтобы мое приложение Java открыло окно консоли / терминала?

Есть ли способ сделать исполняемый файл .jar, который откроет командную строку при двойном щелчке? Я делаю текстовую приключенческую игру. На данный момент это просто лабиринт с комнатами. В конце концов, это будет намного больше и глубже, но пока я просто хочу, чтобы основная структура была опущена. В любом случае, чтобы выполнить эту работу, я получаю вывод и ввод из команды System.out.printf и java.util.Scanner. Все это прекрасно работает до сих пор, но я понял, что у меня возникнут проблемы, когда я попытаюсь отправить это другим людям, которые не знают, как или просто не хотят запускать программу из командной строки.

9 ответов

Если вам нужен полный контроль, вы можете реализовать окно консоли в Swing, которое делает то, что у вас есть сейчас. Если вы не можете открыть указанное окно (если оно не работает), или пользователь запросит его в командной строке, то просто по умолчанию будет действовать ваше текущее поведение.

Я почти ничего не знал о свинге, когда задавал этот вопрос. Изучив его, мне удалось сделать что-то, что не имело ничего общего со сканером, а вместо этого использует JTextArea и JTextField для получения ввода и вывода. Это работает очень хорошо, поэтому спасибо за этот ответ.

Читайте также:  Html css full width and height

Я нашел это, ища ответ самостоятельно, в итоге я написал этот бит:

/** * This opens a command line and runs some other class in the jar * @author Brandon Barajas */ import java.io.*; import java.awt.GraphicsEnvironment; import java.net.URISyntaxException; public class Main< public static void main (String [] args) throws IOException, InterruptedException, URISyntaxException< Console console = System.console(); if(console == null && !GraphicsEnvironment.isHeadless())< String filename = Main.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6); Runtime.getRuntime().exec(new String[]); >else < THEMAINCLASSNAMEGOESHERE.main(new String[0]); System.out.println("Program has ended, please type 'exit' to close the console"); >> > 

не уверен, что мой ответ по-прежнему актуальным, но не стесняйтесь использовать его с комментарием, содержащимся в o/

Единственным недостатком, о котором я могу думать, является то, что он покидает окно cmd после завершения программы.

Использование: поместите этот класс в тот же пакет, что и ваш основной класс, и установите его как основной класс, он откроет окно командной строки, если оно не открыто, или если один из них запускает основной класс. Имя/расположение файла jar автоматически. Предназначен для окон, но если вы хотите, чтобы другая система просто сообщила мне, и я исправлю это. (Я мог бы обнаружить ОС, но я ленив и просто делаю это, поэтому я могу включить файл jar с двойным щелчком моему профессору, который использует окна).

Писать в 2 часа ночи, должен уточнить, я нашел этот пост, пока искал ответ и не увидел ни одного, поэтому я написал это.

Он сказал: «Ошибка: невозможно получить доступ к jarfile C: / 660 / efx / worskspace / . В чем причина? Вы можете это исправить?

@mk7 mk7 вы, вероятно, забыли заменить «THEMAINCLASSNAMEGOESHERE» на предполагаемый основной класс вашего проекта, если нет, дайте мне полное сообщение об ошибке.

Уже заменили ту и другую на две строки выше. Ошибка: «Невозможно получить доступ к jarfile C: / eclipse / workspace / TestConsole / bin /». Я попытался переключиться на другое рабочее пространство, и в окне приглашения cmd все равно остается сообщение об ошибке. Я использовал Eclipse Mars и Java SDK 1.8u60

О, я думаю, я могу знать, что происходит сейчас. Вы пытаетесь запустить его, используя родную среду затмений? Сначала вам нужно скомпилировать его в jar-файл (с этим в качестве основного класса для целей компиляции), затем jar-файл можно будет щелкнуть дважды (нет необходимости в таком скрипте внутри eclipse, поскольку он создает для вас терминальную среду). ).

открытие окна подсказки cmd еще не так полезно. Каждый может легко распечатать инструкцию журнала (используя java.util.logging.Logger) на консоли затмения. Но как вы выводите тот же оператор в это окно командной строки cmd во время выполнения?

Обычно это System.out.println () для этого, но eclipse переопределяет терминальную среду (поэтому он просто будет отображаться в консоли eclipse. Цель этого класса в том, чтобы при компиляции программы командной строки вы могли сделать он дважды кликабелен (как правило, он не будет держать свою собственную терминальную среду открытой).

Источник

How do I make my java application open a console/terminal window?

I found this while looking for an answer myself, I ended up writing this bit:

/** * This opens a command line and runs some other class in the jar * @author Brandon Barajas */ import java.io.*; import java.awt.GraphicsEnvironment; import java.net.URISyntaxException; public class Main< public static void main (String [] args) throws IOException, InterruptedException, URISyntaxException< Console console = System.console(); if(console == null && !GraphicsEnvironment.isHeadless())< String filename = Main.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6); Runtime.getRuntime().exec(new String[]); >else < THEMAINCLASSNAMEGOESHERE.main(new String[0]); System.out.println("Program has ended, please type 'exit' to close the console"); >> > 

not sure if my answer is still relevant, but feel free to use it with the comment kept in o/

Only flaw I can think of is that it leaves the cmd window open after the program completes.

Usage: place this class in the same package as your main class and set it as the main class, it will open a command prompt window if one is not open, or if one is open launch the main class. Name / location of jar file is automatic. Designed for windows, but if you want it for another system just message me and I’ll fix it. (I could do OS detection but I’m lazy and just making this so I can turn in a double-click jar file to my professor who uses windows).

If you want full control, you can implement a Console window in Swing which does what you have now.

If you cannot open said window (if headless) or the user asks for it on the command line, then just default to your current behaviour.

Double-clicking a jar opens it with whatever application you’ve associated to it in your OS. By default, javaw[.exe] is normally associated to jar files. That’s the binary that runs without a terminal window. To see a terminal on double-click, you’d need to associate the java[.exe] binary with jar files.

Источник

How do I display the Java console?

I’m aware of the fact that you can set it to «show» in the Java control panel, but that’s not what I’m asking about. I’m curious about the other options. «Do not start» is pretty straightforward, but what about «Hide»? That would seem to imply that it is indeed running. If so, how can I make it show on demand from the hidden state? Reason: It’s annoying to have it open ALL the time, hoping there’s a way to (preferably via keystroke) bring it from «hidden» to «shown» state for occasional debugging.

2 Answers 2

To view the Java console, right click on the Java icon in the system tray (assuming you’re using Windows) and choose «Open console» — as pictured at the bottom of this page

Good to know. However, my Java icon doesn’t show up in the system tray. I see a Java control panel option «Place Java icon in system tray» under the «Miscellaneous» options. I’ve enabled that, but still don’t see a Java icon in my system tray.

Did you happen to know the Java icon only appears in the system tray after you launch an applet or WebStart app in your browser? If the program is launched from the Windows command line or via an executable, the icon won’t appear. If you are using Firefox, see if there is an «Open Java Console» option under the «Tools» menu. See also this discussion for possible ways to reset it.

The apps that I periodically need to have users pop a console to help in debugging are JNLP/web start apps, and it does not appear when they launch from the browser.

Источник

Console in Java | Example Program

Scientech Easy

Console in Java is a utility class in java.io package that provides access to the system console associated with JVM.

Console class was introduced in Java 1.6 version. It is mainly used for reading data from the console and writing data on the console. All read and write operations are synchronized.

Here, console refers to the character input device (keyboard) and character display device (screen display).

This utility class provides the various methods to access character-based console device connected with JVM (Java Virtual Machine).

Java Console class declaration

Console is a final class that extends Object class and implements Flushable interface. The general syntax to declare console class in java is as follows:

public final class Console extends Object implements Flushable

The inheritance diagram for this console class is as follows:

java.lang.Object java.io.Console

Constructor of Console class

Console class does not provide any constructor in Java. We can create an object reference to the console using System.console() method if JVM is connected to the console.

The syntax to get object reference of console class is as follows:

Console c = System.console(); Here, System is a class that provides a static method console().

If JVM is not connected with any console, this method will return null.

Methods of Console class in Java

In addition to methods inherited from Object class, Java console class also provides some useful methods that are as follows:

1. void flush(): This method flushes the console and forces all buffered output to be written immediately.

2. Console format(String fmtString, Object… args): This method writes a formatted string to this console’s output stream according to the specified format string fmtString and arguments args.

3. Console printf(String format, Object… args): This method writes a formatted string to this console’s output stream using the specified format string and arguments.

4. Reader reader(): It is used to retrieve the Reader object reference associated with this console. That is, this method returns a reference to a Reader connected to the console.

5. String readLine(): The readLine() method is used to read a single line of text from the console. It reads and returns a string entered from the keyboard or user.

Input ends when the user presses ENTER. Null is returned if the end of the console input stream has been reached. On failure, an IOError is thrown.

6. String readLine(String fmtString, Object… args): This method displays a prompting string formatted using specified fmtString and args, and then reads a single line of text from the console.

Input ends when the user presses ENTER. Null is returned if the end of the console input stream has been reached. On failure, an IOError is thrown.

7. char[ ] readPassword(): This method reads a password from the console with echoing.

8. char[ ] readPassword(String fmtString, Object… args): This overloaded method displays a prompting string formatted as specified by fmtString and args, and then reads a password from the console with echoing disabled.

9. PrintWriter writer(): The writer() method is used to retrieve the PrintWriter object reference associated with this console. That is, it returns an object reference to a Writer connected to the console.

Console Example Program

1. Let’s take a simple example program where we will take input from the keyboard or user and display it on the console.

Program code 1:

import java.io.Console; public class ConsoleExample < public static void main(String[] args) < // Create a reference to the console. Console c = System.console(); // Checking the console is available or not. if(c != null) < System.out.printf("Console is available."); >else < System.out.printf("Console is not available."); return; // A console is not available. >// Read a string and then display it on the console. System.out.println("Enter your name: "); String name = c.readLine(); // Reads a line of text from the console. System.out.println("Welcome to " +name); > >
Output: Enter your name: John Welcome to John

In this program, we have used printf() method provided by Java console class. The printf() method displays formatted string on the console. We can also use printf() method of PrintStream class to write the formatted data.

Note : If you execute this program using Eclipse IDE, the console may not be available. Try to execute this program from the command prompt.

2. Let’s create a program where we will read the password using readPassword() method of the console class. If we read the password using Console class, it will not be visible to the user.

Look at the source code to understand better.

Program code 2:

import java.io.Console; public class ConsoleExample < public static void main(String[] args) < // Create a reference to the console. Console c = System.console(); // Checking the console is available or not. if(c != null) < System.out.printf("Console is available."); >else < System.out.printf("Console is not available.%n"); return; >System.out.println("Enter your password: "); char[ ] ch = c.readPassword(); // Reading password. String pass = String.valueOf(ch);// Converting an array of char into string System.out.println("Password is: "+pass); > >
Output: Enter your password: Password is: 1234657

As you can observe in the output, it is not visible when we have entered the password because the program receives it in a character array.

Hope that this tutorial has elaborated all the important points related to Console class in Java with example program. I hope that you will have understood this simple chapter.

In the next tutorial, we will discuss file class in Java with example programs. Please, email us if you find anything incorrect in this tutorial.
Thanks for reading.
Next ⇒ File class in Java ⇐ Prev Next ⇒

Источник

Оцените статью