How to clear the console after a few statements have been executed/printed in Eclipse. I have used flush() but didn't work though. Just posting the sample code.
System.out.println("execute ");
System.out.println("these set of lines ");
System.out.println("first");
Thread.sleep(2000); // just to see the printed statements in the console
System.out.flush(); // it is not clearing the above statements
The Eclipse Console does not support the interpretation of the clear screen and other ANSI escape sequences which would be required for that. Also, the ANSI Escape in Console Eclipse plug-in does not support clear screen.
In the upcoming Eclipse IDE 2019-12 (4.14) which will be released on December 18, 2019, the interpretation of the backslash (\b) and carriage return (\r) characters can be enabled in the preferences (see Eclipse 4.14 - New and Noteworthy - Control character interpretation in Console View):
System.out is a Stream, it makes no sense to clear a stream.
Eclipse's Console is a view that renders that stream and has richer capabilities (including the ability to clear its visible buffer of the stream's content) but the only way to access that is if you were writing an Eclipse plug-in; general Java code has no knowledge of Eclipse's Console view.
You might be able to achieve something moderately useful via some hacks, but I would not recommend relying on it. Usage of System.out in production code is highly discouraged anyway; use a Logger (such as slf4j and logback) instead. And consider what you're really trying to achieve.
It depends on your console but if it supports ANSI escape sequences, then try this..
final static String ESC = "\033[";
System.out.print(ESC + "2J");
Also, you can print multiple end of lines ("\n") and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.
Here is a sample code:
for (int i = 0; i < 50; ++i) System.out.println();
A third option:
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
In case you are talking about eclipse (java console, there is mvn console and svn console as well) then you might want to work with preferences like below:
Go to Window » Preferences to show the Preferences dialog
Go to Run/debug and expand it
Select Console
Here you can now set the console related properties.
Related
I'm trying to do a project for a programming class, and I need to figure out how to be able to get unicode working in J-Creator, if possible. I haven't been able to find anything so far. When I try to print a word in a non-latin alphabet, such as "цитата", it prints "??????". How to I get UTF-8 in J-Creator?
I don't use JCreator, and therefore couldn't verify this answer, but it may still be helpful since there are three general points to consider when rendering UTF-8 text from a Java application to a terminal window:
Assuming that you are using the PrintStream method println() to display your text in JCreator's terminal window, you probably need to instantiate that PrintStream to explicitly use the character encoding UTF-8:
try{
PrintStream outStream = new PrintStream(System.out, true, "UTF-8");
outStream.println("цитата");
} catch(UnsupportedEncodingException e){
// Error handling
}
If you don't do that, and simply call System.out.println("цитата"); instead, then you will be using the default encoding at runtime. That is determined by the JVM during startup, and is unlikely to be UTF-8.
You may need to set the code page in the terminal window to UTF-8. You don't mention your operating system, but from a terminal on Windows (e.g. PowerShell, Command Prompt, etc.) you would call chcp 65001. That may or may not be applicable for your environment, and I have no idea whether JCreator even allows you set the code page when running your application.
You obviously must use a font which supports the text being rendered within the terminal window, which is Russian in your case. I don't know how JCreator determines the font to use and whether it allows you to explicitly set that font, but it can be set for a Command Prompt window on Windows.
It's possible that despite your best efforts the JCreator terminal simply won't support what you want to do. In that case your workaround will be to use a terminal window supported by your operating system and run your application there, assuming that you are able to set the code page and the font.
What I do:
public class Main {
public static void main(String[] args) {
char i = 0x25A0;
System.out.println(i);
i = 0x2612;
System.out.println(i);
i = 0x2610;
System.out.println(i);
}
}
What I get in IDE:
What I get in IDE
What I get in Windows console:
What I get in Windows console
I have Windows 10 (Russian locale), Cp866 default coding in console, UTF-8 coding in IDE.
How to make characters in console look correct?
Two problems here, actually:
Java converts output to its default encoding which doesn't have anything to do with the console encoding, usually. This can apparently only be overridden at VM startup with, e.g.
java -Dfile.encoding=UTF-8 MyClass
The console window has to use a TrueType font in order to display Unicode. However, neither Consolas, nor Lucida Console have ☐, or ☒. So they show up as boxes with Lucida Console and boxes with a question mark with Consolas (i.e. the missing glyph glyph). The output is still fine, you can copy/paste it easily, it just doesn't look right, and since the Windows console doesn't use font substitution (hard to do that with a character grid anyway), there's little you can do to make them show up.
I'd probably just use [█], [ ], and [X] instead.
Cp866 default coding in console
well yeah. Code page 866 doesn't include characters U+25A0, U+2610 or U+2612. So even if Java were using the correct encoding for the console (either because you set something like -Dfile.encoding=cp866, or it guessed the right encoding, which it almost never manages), you couldn't get the characters out.
How to make characters in console look correct?
You can't.
In theory you could use -Dfile.encoding=utf-8, and set the console encoding to UTF-8 (or near enough, code page 65001). Unfortunately the Windows console is broken for multi-byte encodings (other than the legacy locale-default supported ones, which UTF-8 isn't); you'll get garbled output and hangs on input. This approach is normally unworkable.
The only reliable way to get Unicode to the Windows console is to skip the byte-based C-standard-library I/O functions that Java uses and go straight to the Win32 native WriteConsoleW interface, which accepts Unicode characters (well, UTF-16 code units, same as Java strings) and so avoids the console bugs in byte conversion. You can use JNA to access this API—see example code in this question: Java, UTF-8, and Windows console though it takes some extra tedious work if you want to make it switch between console character output and regular byte output for command piping.
And then you have to hope the user has non-raster fonts (as #Joey mentioned), then then you have to hope the font has glyphs for the characters you want (Consolas doesn't for U+2610 or U+22612). Unless you really really have to, getting the Windows console to do Unicode is largely a waste of your time.
Are you sure, that the font you use, has characters to display the Unicode? No font supports every possible Unicode character. U+9744,9632 and 9746 are not supported by e.g. the Arial font. You can Change the font of your IDE console and your Windows console too.
I have just started learning Java with IntelliJ IDE. I know a bit C# so the logic makes some sense, however there is one thing so far I couldn't get over it.
How do I read from the console? In C#, you could easily read what the human typed into it, using Console.ReadLine(). In Java, System.console().readLine(); does not work for me and throws a NullPointerException.
What am I missing here?
NOTE: problem doesn't appear when we run your code from console/terminal via java [options] [MainClass] so if this is valid solution for you you can stop reading here. Rest of this answer is for people who are using some IDEs to run their code.
Problem
Most IDEs are using javaw.exe instead of java.exe to run Java code (see image below).
Difference between these two programs is that javaw runs Java code without association with current terminal/console (which is useful for GUI applications), and since there is no associated console window System.console() returns null. Because of that System.console().readLine() ends up as null.readLine() which throws NullPointerException since null doesn't have readLine() method (nor any method/field).
But just because there is no associated console, it doesn't mean that we can't communicate with javaw process. This process still supports standard input/output/error streams, so IDEs process (and via it also we) can use them via System.in, System.out and System.err.
This way IDEs can have some tab/window and let it simulate console.
For instance when we run code like in Eclipse:
package com.stackoverflow;
public class Demo {
public static void main(String[] args) throws Exception {
System.out.println("hello world");
System.out.println(System.console());
}
}
we will see as result
which shows that despite javaw.exe not having associated console (null at the end) IDE was able to handle data from standard output of the javaw process System.out.println("hello world"); and show hello world.
General solution
To let user pass information to process use standard input stream (System.in). But since in is simple InputStream and Streams are meant to handle binary data it doesn't have methods which would let it easily and properly read data as text (especially if encoding can be involved). That is why Readers and Writers ware added to Java.
So to make life easier and let application read data from user as text you can wrap this stream in one of the Readers like BufferedReader which will let you read entire line with readLine() method. Unfortunately this class doesn't accept Streams but Readers, so we need some kind of adapter which will simulate Reader and be able to translate bytes to text. But that is why InputStreamReader exists.
So code which would let application read data from input stream could look like
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Hello. Please write your name: ");
String name = br.readLine();
System.out.println("Your name is: "+name);
Preferred/simplest solution - Scanner
To avoid this magic involving converting Stream to Reader you can use Scanner class, which is meant to read data as text from Streams and Readers.
This means you can simply use
Scanner scanner = new Scanner(System.in);
//...
String name = scanner.nextLine();
to read data from user (which will be send by console simulated by IDE using standard input stream).
If you realy need to Console object you can compile your class from command line. Firstly in my java file first statement is package com.inputOutput;
Go in your project "src" folder and compile it like : "javac com/inputOutput/Password.java" 'com' and 'inputOutput' are folder(package). Run your class file in src folder
java com.inputOutput.Password". It had worked work for me.
You could use an Jframe.
JFrame frame = new JFrame("titile");
// prompt the user to enter their code
String code = JOptionPane.showInputDialog(frame, "promt here");
java.util.Scanner API is what you are looking for.
This question already has answers here:
How to clear the console?
(14 answers)
Closed 7 years ago.
Is there any option to clear the screen in java as clrscr() in C.
As dirty hacks go, I like msparer's solution. An even dirtier method that I've seen used (I would never do this myself. I swear. Really.) is to write a bunch of newlines to the console. This doesn't clear the screen at all, but creates the illusion of a clear screen to the user.
char c = '\n';
int length = 25;
char[] chars = new char[length];
Arrays.fill(chars, c);
System.out.print(String.valueOf(chars));
If you're talking about a console application, then there isn't a clear screen option AFAIK. A quite dirty option would be to invoke the clear screen command of the underlying OS.
Then it's something like
Runtime.getRuntime().exec("cls");
for Windows or
Runtime.getRuntime().exec("clear");
for a load of other OS. You can find out the OS with System.getProperty("os.name").
If you're talking about the console, then no. Writing to the console is just a special case of an output stream. Output streams don't know anything about the screen, as they can be just as easily redirected to a file or another system device.
For any console which supports ANSI escapes the following would work (would e.g. work in Win98 console).
private final String ANSI_CLS = "\u001b[2J";
....
System.out.print(ANSI_CLS);
System.out.flush();
...
Starting with Win NT this won't work anymore and you can either
Do a JNI call (e.g. like here: Java: Clear console and control attributes
Or write out a bunch of empty lines
Otherwise you are out of luck.
And btw. you must keep in mind that System.out and System.err don't have to be console they could be set to what ever (writing into a file e.g.) an usecase where clearing the screen wouldn't make any sense at all.
On linux, you can do something like:
System.out.println("\f");
You can also use Jcurses
To clear the screen just type:
System.out.print('\u000C');
You can also try ANSI Escape Codes:
If your terminal support them, try something like this:
System.out.print("\033[2J\033[1;1H");
You can include \0333[1;1H to be sure if \0333[2J does not move the cursor in the upper left corner.
More specifically:
033 is the octal of ESC
2J is for clearing the entire console/terminal screen
1;1H moves the cursor to row 1 and column 1
Jansi is an excellent workaround. I am an amateur coder and Jansi is easy to setup especially with Eclipse.
The following is a link to the homepage of Jansi:
http://jansi.fusesource.org/
The following is a link to a site containing a code as a demonstration of AnsiConsole class contained in the Jansi package:
http://www.rgagnon.com/javadetails/java-0047.html
For Windows, Java Console API project provides functionality to determine console size and set cursor position. Clearing the screen is trivial with that. It's a version 0.2 now so it's not exactly production ready, but it works.
Alternatively, you can simply print out some new lines via System.out.println(). 640 should be enough for everybody :-) It's not the same as clearing screen, but for user's intents and purposes it'd do.
you should give a try with JNA and try mapping native libraries:
on linux you must map C functions from ncurses library
on windows you must map functions from both msvcrt and kernel32, as clearly stated here
PS
let me known if you need some sample code
Does Java support controlling the cursor when outputting to a console? For example, I'd like to set the character position, and possibly color, before doing a System.out.print(). Think of the way an application like top writes to the console. Thanks!
You usually do not use system.out to do these things. most applications in *nix use NCURSES (http://en.wikipedia.org/wiki/Ncurses) for this. You can try http://sourceforge.net/projects/javacurses/ if you need something this smart.
However, you can always sysout backspace (\b) characters if you want to delete what you wanted, and hope for the best
Ha. You can still do it in Linux.
Reference this man page for the codes themselves
http://man7.org/linux/man-pages/man4/console_codes.4.html
public class quickTest{
public static void main( String[] args ){
//This will undo the current line by erasing it
//and then putting the curser back at column 1
System.out.println( "Hello.\u001b[1K\u001b[1GHi." );
}
}
Not directly. In the old days ANSI escape sequences was supported, but not anymore.
I would suggest you look into a good Java Curses library supporting Windows. I cannot recommend any :(