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:
Search for code examples on this site
