Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output as UTF-8 encoding in java

I am having problem with the output file from a program using eclipse .i set my eclipse to UTF-8 and with

 System.getProperty("file.encoding") 

i get UTF-8.i ran my prog via eclipse run-option and the output (a text file) is encoded in UTF-8.but when i compressed the source code into a jar file,the output file shows error in some of the alphabet like Ã.what is with this diff when ruuning the prog in eclipse and frm jar file?and do i have to specify the output to be encoded in utf-8 in my source code?pls help.

help from @dacwe indeed produced the desired output.but may i know how can i run my executable .jar file outside command line?how can the -Dfile.encoding=UTF-8

@dacwe :i tried changing my source code into

 BufferedWriter bout  = new java.io.BufferedWriter(new java.io.OutputStreamWriter(
                new java.io.FileOutputStream(filename), "UTF-8"));

but the output still is not encoded correctly.anything i miss here?

like image 737
reukEN11 Avatar asked Jul 18 '11 12:07

reukEN11


2 Answers

After some major discussion in @Dave G's answer!

Using java -Dfile.encoding=UTF-8 -jar your-jar-file.jar works.

Updating your code as @Dave G suggested (and your edit) should work.

  • Have you really repackaged your jar?
  • Do you call close() on bout? (e.g. maybe your file isn't updated)

Here is a full example that might get you going:

public static void main(String... args) throws Exception {
    PrintWriter out = new PrintWriter(new File("hello.txt"), "UTF-8");
    out.print("written in utf-8");
    out.close();
}
like image 178
dacwe Avatar answered Sep 23 '22 09:09

dacwe


When you run from a JAR file are you setting the file.encoding property by -Dfile.encoding? If not, you can either

a) open the stream explicitly with that encoding. for this you will have to create an OutputStream and then wrap that in an OutputStreamWriter explicitly indicating the character encoding.

or

b) set the property as the first thing in your main method using System.setProperty("file.endcoding");

note @dacwe pointed out something I forgot ... corrected my answer.

like image 28
Dave G Avatar answered Sep 22 '22 09:09

Dave G