Printing text with the Console class


When you're using the System.out to print non-english characters you might have noticed that they're translated to some odd characters that you didn't intend to write.
In Java 6 there is a new Console class that can be retrieved by calling the System.console() method. That'll give you access to an object that is capable of printing the characters to the console as you want to.
In the example below we write some typical characters that are messed up when using the System.out call.

The output from the code below is one line with completely different characters than intended and one line where the characters are displayed correctly.



import java.io.Console;

/**
 *
 * @author javadb.com
 */

public class Main {
    
    /**
     * Example method for using the Console class to print text
     */

    public void consoleExample() {
        
        String s = "Some test characters: å ä ö Å Ä Ö";
        
        //Prints partly rubbish
        System.out.println(s);
        
        Console console = System.console();
        
        if (console == null)
            System.out.println("Couldn't get Console object, maybe you're running this from within an IDE?");
        else
            //Prints the characters correctly
            console.printf("%s%n", s);
    }
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().consoleExample();
    }
}

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark: Social bookmarks del.icio.us digg Furl YahooMyWeb blinkbits BlinkList blogmarks co.mments connoteas De.lirio.us Fark feedmelinks LinkaGoGo Ma.gnolia NewsVine Netvouz RawSugar Reddit scuttle Shadows Simpy Smarking Spurl TailRank Wists segnalo




   Need Java help? You are just a few bucks away.

   This is how it works:
  • Send us a detailed description of what you need help with.
  • We send you a confirmation when we start working on your request, and then we send you the compiled Java code for you to test out.
  • If you are satisfied with the result we send you a secure link where you can make the payment for the Java source code, usually a few bucks (depends on the work required).
  • The source code is sent to you once the payment is completed.


Write your detailed request here:
   

E-mail address: