Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Jeremiah Shore
Jeremiah Shore
31,168 Points

Is it possible to clear the console during execution in a Java workspace?

I am trying to create a text based RPG game for some practice of the topics covered in Java Basics and Java Objects. I want to refresh the console every time something happens, clearing the data and displaying everything in the top left corner.

I tried implementing this to clear the console, but the clear command definitely does not work:

private 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) {
        mConsole.printf("something went wrong :(");
    }
  }

I am not sure how the workspace platform operates, I am assuming it is linux or unix based. Running "clear" from the command line obviously works, but I need it to happen during execution to get the information displayed precisely as I would like it.

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Hey Jeremiah!

Looking forward to seeing your game!

You can achieve a clear using ASCII Escape codes like so:

System.out.print("\033[H\033[2J");

PS. I copy and pasted that ;) Here's more explanation.

Good luck!

Jeremiah Shore
Jeremiah Shore
31,168 Points

Craig, that works just like I needed it to. Thanks!

I'll be sure to share the source files when I'm done.

Jeremiah Shore
Jeremiah Shore
31,168 Points

This project is still in the works. When I went to refactor the code after a week or two of android experience I found that doing so manually would be a burden. I decided instead to copy everything to eclipse to use its powerful refactoring tools.

In doing so I "broke" the ability to use the escape code. Both the Eclipse console emulator and the Windows command prompt (I'm on win 7) do not support ANSI. I found that the sloppy way of clearing the console by printing a bunch of blank lines is going to be a more versatile solution, in that it will work on probably any system running it, including workspaces. I've come to the conclusion that being able to clear the console the "correct" way isn't really that important, when I'd rather have this code work in Eclipse AND in workspaces for when I share it later.