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
Brian Pedigo
26,786 PointsClear console with a Java Method
I am trying to write a method in Java that clear the console. However, I haven't been able to come up with anything successful. I have come up with the following code but it doesn't seem to work. I understand there is a work around by creating a method that prints a lot of new lines to the screen but that's not quite what I was looking for. If anyone has some ideas on how to do this that would be awesome!
public void cls()
{
try
{
Runtime.getRuntime().exec("cmd /c cls");
}
catch(final Exception e)
{
System.out.print(e);
}
}
1 Answer
Ken Alger
Treehouse TeacherBrian;
One method to use which would also provide support for Windows and Linux operating systems would be something similar to:
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.
Happy coding,
Ken
sradms0
Treehouse Project Reviewersradms0
Treehouse Project ReviewerLinux is a kernel, not an OS. It is most likely GNU/Linux that you are referring to.