TheMaskedCucumber
TheMaskedCucumber

Reputation: 2039

From a Java program, portable way to write strings with accents

Hullo,

I have a Java program, with command line interface. It is used on Linux and Windows. The Java code is portable, and I want it to remain portable.

My Java source files are in Unicode — which is good. In them, I have lines like this :

System.err.println("Paramètre manquant. … ");

I use Eclipse to package the program as a JAR archive.

Then, the program is run by a command like this :

java -jar MyProgram.jar parameters

In the Windows XP command line, this gives :

ParamÞtre manquant. … 

Is there a portable way to write strings with accents in the Java program, so that they appear correctly in the Windows command line ? Or do we just have to live with Windows stupidly replacing accented E with icelandic thorn ?

I use Java 6.

Upvotes: 4

Views: 2975

Answers (3)

RealHowTo
RealHowTo

Reputation: 35397

In Java 1.6 you can use System.console() instead of System.out.println() to display accentuated characters to console.

public class Test2 {
  public static void main(String args[]){
   String s = "caractères français :  à é \u00e9"; // Unicode for "é"
   System.out.println(s);
   System.console().writer().println(s);
  }
}

and the output is

C:\temp>java Test
caractþres franþais :  Ó Ú Ú
caractères français :  à é é

Upvotes: 6

Alepac
Alepac

Reputation: 1831

Use unicode escaped sequence: \u00E8

System.err.println("Param\u00E8tre manquant. … ");

Here's an useful Unicode character table.

Upvotes: 3

fcm
fcm

Reputation: 6463

Try using \u<XXXX> when encoding unicode characters. It won't look pretty in code, but it will work and be portable.

For instance:

String specialCharacters= "\u00E1 \u00E9 \u00ED \u00F3 \u00FA";
System.out.println(specialCharacters); // This will print á é í ó ú

Check Alepac's answer for a table of unicode characters.

Upvotes: 1

Related Questions