Yes it does raise cross platform issues, as to do it you must target the OS for its commands to do so.
For example on windows, this is how you would go about it.
Console.h
#include <jni.h>
/* Header for class Console */
#ifndef _Included_Console
#define _Included_Console
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Console
* Method: clr
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Console_clr
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Console.c
#include <windows.h>
#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_Console_clr(JNIEnv *, jobject){
/*
* Get Console HANDLE for control
*/
HANDLE chwnd = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coordScreen = { 0, 0 };
DWORD cCharsWritten;
/*
* Ensure text colours are stored and set
*/
{
WORD textColours;
CONSOLE_SCREEN_BUFFER_INFO *consoleInfo = new CONSOLE_SCREEN_BUFFER_INFO();
GetConsoleScreenBufferInfo(chwnd, consoleInfo);
textColours = consoleInfo->wAttributes;
SetConsoleTextAttribute(chwnd, textColours);
}
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD dwConSize;
/*
* If fail to get Console Dimensions, return
*/
if( !GetConsoleScreenBufferInfo( chwnd, &csbi ))
return;
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
/*
* Return on error when filling the screen with ' '
*/
if( !FillConsoleOutputCharacter( chwnd, (TCHAR) ' ',
dwConSize, coordScreen, &cCharsWritten ))
return;
if( !GetConsoleScreenBufferInfo( chwnd, &csbi ))
return;
if( !FillConsoleOutputAttribute( chwnd, csbi.wAttributes,
dwConSize, coordScreen, &cCharsWritten ))
return;
/*
* Return Cursor to Origin of Console
*/
SetConsoleCursorPosition( chwnd, coordScreen );
return;
}
#ifdef __cplusplus
}
#endif
Compile with under G++
g++ -Wall -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -I"C:/Program Files/Java/jdk1.6.0_14/include" -I"C:/Program Files/Java/jdk1.6.0_14/include/win32" -shared ConsoleClear.c -o ConsoleClear.dll
Console.java
/*
* Usage: Console.clr()
*/
public class Console {
/*
* Load External DLL for clr Function
*/
static {
System.loadLibrary("ConsoleClear");
}
public static native void clr();
}
Example usage
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
System.out.print("Hello, shall I clear the screen? (y/n) :> ");
if(new Scanner(System.in).nextLine().equalsIgnoreCase("y")){
Console.clr();
System.out.println("Console Cleared!");
}else{
System.out.println("Console not cleared!");
}
}
}
The reason why clearing is frowned upon is because applications running in the console can quite often me running just after other applcations have been executed, and clearing the console should not be done because it will clear the output of the previous applications data.
Chris