How to delete stuff printed to console by System.out.println()? - java

In a Java application I'm using some calls to System.out.println(). Now I want to find a way to programmatically delete this stuff.
I couldn't find any solution with google, so are there any hints?

You could print the backspace character \b as many times as the characters which were printed before.
System.out.print("hello");
Thread.sleep(1000); // Just to give the user a chance to see "hello".
System.out.print("\b\b\b\b\b");
System.out.print("world");
Note: this doesn't work flawlessly in Eclipse console in older releases before Mars (4.5). This works however perfectly fine in command console. See also How to get backspace \b to work in Eclipse's console?

Clearing screen in Java is not supported, but you can try some hacks to achieve this.
a) Use OS-depends command, like this for Windows:
Runtime.getRuntime().exec("cls");
b) Put bunch of new lines (this makes ilusion that screen is clear)
c) If you ever want to turn off System.out, you can try this:
System.setOut(new PrintStream(new OutputStream() {
#Override public void write(int b) throws IOException {}
}));

You could use cursor up to delete a line, and erase text, or simply overwrite with the old text with new text.
int count = 1;
System.out.print(String.format("\033[%dA",count)); // Move up
System.out.print("\033[2K"); // Erase line content
or clear screen
System.out.print(String.format("\033[2J"));
This is standard, but according to wikipedia the Windows console don't follow it.
Have a look: http://www.termsys.demon.co.uk/vtansi.htm

I am using blueJ for java programming. There is a way to clear the screen of it's terminal window. Try this:-
System.out.print ('\f');
this will clear whatever is printed before this line. But this does not work in command prompt.

System.out is a PrintStream, and in itself does not provide any way to modify what gets output. Depending on what is backing that object, you may or may not be able to modify it. For example, if you are redirecting System.out to a log file, you may be able to modify that file after the fact. If it's going straight to a console, the text will disappear once it reaches the top of the console's buffer, but there's no way to mess with it programmatically.
I'm not sure exactly what you're hoping to accomplish, but you may want to consider creating a proxy PrintStream to filter messages as they get output, instead of trying to remove them after the fact.

To clear the Output screen, you can simulate a real person pressing CTRL + L (which clears the output). You can achieve this by using the Robot() class, here is how you can do this:
try {
Robot robbie = new Robot();
robbie.keyPress(17); // Holds CTRL key.
robbie.keyPress(76); // Holds L key.
robbie.keyRelease(17); // Releases CTRL key.
robbie.keyRelease(76); // Releases L key.
} catch (AWTException ex) {
Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
}

There are two different ways to clear the terminal in BlueJ. You can get BlueJ to automatically clear the terminal before every interactive method call. To do this, activate the 'Clear screen at method call' option in the 'Options' menu of the terminal. You can also clear the terminal programmatically from within your program. Printing a formfeed character (Unicode 000C) clears the BlueJ terminal, for example:
System.out.print('\u000C');

Just to add to BalusC's anwswer...
Invoking System.out.print("\b \b") repeatedly with a delay gives an exact same behavior as when we hit backspaces in {Windows 7 command console / Java 1.6}

I've found that in Eclipse Mars, if you can safely assume that the line you replace it with will be at least as long as the line you are erasing, simply printing '\r' (a carriage return) will allow your cursor to move back to the beginning of the line to overwrite any characters you see. I suppose if the new line is shorter, you can just make up the different with spaces.
This method is pretty handy in eclipse for live-updating progress percentages, such as in this code snippet I ripped out of one of my programs. It's part of a program to download media files from a website.
URL url=new URL(link);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.connect();
if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Response "+connection.getResponseCode()+": "+connection.getResponseMessage()+" on url "+link);
}
long fileLength=connection.getContentLengthLong();
File newFile=new File(ROOT_DIR,link.substring(link.lastIndexOf('/')));
try(InputStream input=connection.getInputStream();
OutputStream output=new FileOutputStream(newFile);)
{
byte[] buffer=new byte[4096];
int count=input.read(buffer);
long totalRead=count;
System.out.println("Writing "+url+" to "+newFile+" ("+fileLength+" bytes)");
System.out.printf("%.2f%%",((double)totalRead/(double)fileLength)*100.0);
while(count!=-1)
{
output.write(buffer,0,count);
count=input.read(buffer);
totalRead+=count;
System.out.printf("\r%.2f%%",((double)totalRead/(double)fileLength)*100.0);
}
System.out.println("\nFinished index "+INDEX);
}

The easiest ways to do this would be:
System.out.println("\f");
System.out.println("\u000c");

For intellij console the 0x08 character worked for me!
System.out.print((char) 8);

I found a solution for the wiping the console in an Eclipse IDE. It uses the Robot class. Please see code below and caption for explanation:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public void wipeConsole() throws AWTException{
Robot robbie = new Robot();
//shows the Console View
robbie.keyPress(KeyEvent.VK_ALT);
robbie.keyPress(KeyEvent.VK_SHIFT);
robbie.keyPress(KeyEvent.VK_Q);
robbie.keyRelease(KeyEvent.VK_ALT);
robbie.keyPress(KeyEvent.VK_SHIFT);
robbie.keyPress(KeyEvent.VK_Q);
robbie.keyPress(KeyEvent.VK_C);
robbie.keyRelease(KeyEvent.VK_C);
//clears the console
robbie.keyPress(KeyEvent.VK_SHIFT);
robbie.keyPress(KeyEvent.VK_F10);
robbie.keyRelease(KeyEvent.VK_SHIFT);
robbie.keyRelease(KeyEvent.VK_F10);
robbie.keyPress(KeyEvent.VK_R);
robbie.keyRelease(KeyEvent.VK_R);
}
Assuming you haven't changed the default hot key settings in Eclipse and import those java classes, this should work.

BalusC answer didn't work for me (bash console on Ubuntu). Some stuff remained at the end of the line. So I rolled over again with spaces. Thread.sleep() is used in the below snippet so you can see what's happening.
String foo = "the quick brown fox jumped over the fence";
System.out.printf(foo);
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul("\b", foo.length()));
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul(" ", foo.length()));
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul("\b", foo.length()));
where mul is a simple method defined as:
private static String mul(String s, int n) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < n ; i++)
builder.append(s);
return builder.toString();
}
(Guava's Strings class also provides a similar repeat method)

I have successfully used the following:
#Before
public void dontPrintExceptions() {
// get rid of the stack trace prints for expected exceptions
System.setErr(new PrintStream(new NullStream()));
}
NullStream lives in the import com.sun.tools.internal.xjc.util package so might not be available on all Java implementations, but it's just an OutputStream, should be simple enough to write your own.

this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs.
PrintStream ps = System.out;
System.setOut(new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {}
}));
System.out.println("It will not print");
//To again enable it.
System.setOut(ps);
System.out.println("It will print");

Related

how to clear console in java (using eclipse) [duplicate]

Can any body please tell me what code is used for clear screen in Java?
For example, in C++:
system("CLS");
What code is used in Java to clear the screen?
Since there are several answers here showing non-working code for Windows, here is a clarification:
Runtime.getRuntime().exec("cls");
This command does not work, for two reasons:
There is no executable named cls.exe or cls.com in a standard Windows installation that could be invoked via Runtime.exec, as the well-known command cls is builtin to Windows’ command line interpreter.
When launching a new process via Runtime.exec, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls command gets redirected, it doesn’t clear the console.
To solve this problem, we have to invoke the command line interpreter (cmd) and tell it to execute a command (/c cls) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using inheritIO():
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.
You can use following code to clear command line console:
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
Caveats:
This will work on terminals that support ANSI escape codes
It will not work on Windows' CMD
It will not work in the IDE's terminal
For further reading visit this
This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).
public final static void clearConsole()
{
try
{
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
{
Runtime.getRuntime().exec("cls");
}
else
{
Runtime.getRuntime().exec("clear");
}
}
catch (final Exception e)
{
// Handle any exceptions.
}
}
⚠️ Note that this method generally will not clear the console if you are running inside an IDE.
A way to get this can be 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();
Try the following :
System.out.print("\033\143");
This will work fine in Linux environment
Create a method in your class like this: [as #Holger said here.]
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
This works for windows at least, I have not checked for Linux so far. If anyone checks it for Linux please let me know if it works (or not).
As an alternate method is to write this code in clrscr():
for(int i = 0; i < 80*300; i++) // Default Height of cmd is 300 and Default width is 80
System.out.print("\b"); // Prints a backspace
I will not recommend you to use this method.
If you want a more system independent way of doing this, you can use the JLine library and ConsoleReader.clearScreen(). Prudent checking of whether JLine and ANSI is supported in the current environment is probably worth doing too.
Something like the following code worked for me:
import jline.console.ConsoleReader;
public class JLineTest
{
public static void main(String... args)
throws Exception
{
ConsoleReader r = new ConsoleReader();
while (true)
{
r.println("Good morning");
r.flush();
String input = r.readLine("prompt>");
if ("clear".equals(input))
r.clearScreen();
else if ("exit".equals(input))
return;
else
System.out.println("You typed '" + input + "'.");
}
}
}
When running this, if you type 'clear' at the prompt it will clear the screen. Make sure you run it from a proper terminal/console and not in Eclipse.
Runtime.getRuntime().exec(cls) did NOT work on my XP laptop. This did -
for(int clear = 0; clear < 1000; clear++)
{
System.out.println("\b") ;
}
Hope this is useful
By combining all the given answers, this method should work on all environments:
public static void clearConsole() {
try {
if (System.getProperty("os.name").contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
else {
System.out.print("\033\143");
}
} catch (IOException | InterruptedException ex) {}
}
Try this: only works on console, not in NetBeans integrated console.
public static void cls(){
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c",
"cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
This will work if you are doing this in Bluej or any other similar software.
System.out.print('\u000C');
You can use an emulation of cls with
for (int i = 0; i < 50; ++i) System.out.println();
You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.
Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it
After these configurations, you can manage your console with control characters like:
\t - tab.
\b - backspace (a step backward in the text or deletion of a single character).
\n - new line.
\r - carriage return. ()
\f - form feed.
More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php
You need to use JNI.
First of all use create a .dll using visual studio, that call system("cls").
After that use JNI to use this DDL.
I found this article that is nice:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=5170&lngWId=2

Program provides correct output for println(String s); but not print(String s); why?

Below is a code I'm having issues with:
public class testOutput {
public static void main(String[] args) throws Exception {
int count = 50000;
String s = "Vinjith";
for(int i=0;i<count;i++) {
System.out.print(s); // change this to println(s); and it works!
System.out.flush();
}
}
}
I'm using Eclipse Galileo - jdk 1.6/ jre6.
I've set no limit on the console output.
I've also tried the same program with BufferedWriter: doesn't work
It works when the variable count = 584; not more than that.
I do not get any output when i use System.out.print(s); but when i use System.out.println(s); i get 50000 lines of the string 'Vinjith'.
Thanks.
This is because of having too much characters on the same line, where Eclipse does not support that on its console (You will see nothing printing on the console). Try the same code on the command line and it should work.
This is because the length of the characters you're printing on Eclipse console is going beyond the limits.
Try this and see if it prints or not.
System.out.print(s); // change this to println(s); and it works!
System.out.println();
System.out.flush();
Also, regarding the limit issue, just try this out. In the preferences - > run/debug -> console, there will an check box called Fixed Width Console. Its max limit is 1000. Try to make it 1000 and run your original code as below. You'll see that it prints some characters and for the rest, throws up an Internal Error.
System.out.print(s); // change this to println(s); and it works!
System.out.flush();
Have you tried this:
for(int i=0;i<count;i++) {
System.out.print(s); // change this to println(s); and it works!
}
System.out.println("---done");
System.out.flush();
What happens when you try values of count (100, 500, 1000, 2000, 10000, etc.)?
Please post output from when it works and what 'count' is.
I've looked into issues with flush() before and it comes down to how your OS internally handles buffers. Most JRE's only define the interface and then rely on the OS to implement the actual behavior and in some cases it gets weird. See my answer to a similiar question.

Writing long string in Java to file

I'm trying to dump a large integer array (10 000 elements) into a text file but am encountering some problems. I've tried two different approaches and neither seems to be working. Below is the function I've written:
private static void writeToFile(String name, int[] a){
try {
FileWriter fw = new FileWriter(name);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("working");
for (int n: a){
bw.write(n + " ");
}
bw.close();
} catch (IOException e) {
System.err.print("Unable to write to file " + name+ ".");
e.printStackTrace();
}
}
The first thing I tried was creating a string in the for loop and then writing the whole string to the file. Neither method works and gives me the same results as follows:
File is created but left blank
Works fine for shorter arrays (~10 elements)
Works fine if the space is a letter eg: bw.write(n + "a")
Any idea what I'm doing wrong? Or is there an even easier way that I'm not seeing?
Thanks,
Civatrix
Can you explain how you're viewing/reading in the file afterwards? Your code is basically fine as far as I can see (bar moving the close() to a finally block), and it really should make no difference whatsoever whether a space or other letter is added. But that might make a difference e.g. to a text editor, I suppose...?
That code will write all the elements of a[] to the file followed by a space, unless it gets an exception. However it won't write any lines. Is that your problem? If so, you need bw.newLine() after each write().

Outputing text to a file?

After running my program I get this beautifully formatted text:
What do I need add to my code in order to get this text outputted to a .txt file exactly as is?
Assuming you're currently writing your output to the screen using something like System.out.Println(...), a comparable way to write text to a file is to use a PrintStream.
You should be able to find many examples of how to do that if you search; here's one.
import java.io.*;
class PrintStreamDemo {
public static void main(String args[]){
FileOutputStream out;
PrintStream ps; // declare a print stream object
try {
// Create a new file output stream
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
ps = new PrintStream(out);
ps.println ("This data is written to a file:");
System.err.println ("Write successfully");
ps.close();
}
catch (Exception e){
System.err.println ("Error in writing to file");
}
}
}
ps. one caution: the "beautifully formatted" part of your text probably relies on the output being displayed in a monospaced font (all characters the same width); if viewed in a non-monospaced font, the columns won't line up. If you're saving it as a plain .txt file, you don't have control over what font someone else will use to display that file when they open it.
Update:
There are a couple of approaches you could take, if you find you've got a program full of System.out.println calls and you want to direct the output to a file instead.
1) The quick & dirty way would be to open a PrintStream to your desired output file, then call System.setOut() to redirect System.out to the specified PrintStream.
2) A perhaps cleaner way would be to rewrite all the calls of System.out.println to use your own output method. That way when you want to change how you're handling output (for example, send it to multiple files, to both the screen and a file, or whatever), you have just one place to change. More work up front, but gives you more flexibility in the end.
You didnt clarify where data come from, but anyway input or db, I would place on a multidimensional array. Then print will be easy.
P.S. Also to keep format I would use tab separated values "/t"
public class Parser {
private void parseData{
int[][] array = new int[3][12];
// print array in rectangular form
for (int r=0; r<array.length; r++) {
for (int c=0; c<array[r].length; c++) {
System.out.print(array[r][c] + "\t");
}
System.out.println("");
}
}
}

How do I catch a java.io.PrintStream place its output in a JEditorPane?

I am attempting to make a Java program in which a user can select any .class or .jar file from their computer. My program will then pop up a JInternalFrame with a JEditorPane in it as the console, capturing any console output from the user's program. Note that I do not want to capture just System.err or System.out calls, but ALL PrintStream calls that go to the console.
(individual question from IDE-Style program running )
You can catch everything that is printed through System.out using System.setOut like this:
import java.io.*;
class SystemOutLogging {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
final PrintStream original = System.out;
System.setOut(new PrintStream("programlog.txt") {
public void println(String str) {
process(str + "\n");
}
public void print(String str) {
process(str);
}
private void process(String str) {
// Fill some JEditorPane
original.println("Program printed: \"" + str + "\"");
}
});
System.out.print("Hello ");
System.out.println(" World");
}
}
Prints:
Program printed: "Hello "
Program printed: " World
"
(There is a System.setErr and System.setIn that works similarly.)
If you want to catch stuff that the "subprogram" prints through System.out.println you're in trouble, because System.out is a static so if you launch multiple "subprograms" you'll end up with a mess (since you can't hand a separate System class to each subprogram).
In a situation like this, I honestly think it would be a better idea to launch a separate process through ProcessBuilder. The standard input / output streams of the resulting process could easily be logged.
(p.s. When I think about it, you could probably check the current thread group in the println implementation, and from that decide which subprogram that actually invoked the println method)
If you're starting the user's .jar file using Runtime.exec(), you'll get a Process object. That Object will allow you access to the launched processes System.out, System.in and System.err streams.
See: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html
You can take read from the err and out streams, and append to your JEditorPane using the usual setText type methods.

Categories