BladeHal
BladeHal

Reputation: 783

Java and Unicode

I have an app that converts an html to an excel spreadsheet using java. There are some characters that are not being rendered correctly in excel. More than likely an encoding problem. I need a way to convert those strings in java to unicode (UTF-16) so they would be rendered correctly by excel.

Upvotes: 2

Views: 940

Answers (2)

beny23
beny23

Reputation: 35008

Assuming you've got the content in your Java app, you need to make sure that you write your file with the correct encoding.

To specify a particular encoding, you'll have to create an OutputStreamWriter:

Writer out = new BufferedWriter(
                 new OutputStreamWriter(
                     new FileOutputStream(file), "UTF-16"));

Upvotes: 3

Daniel Rikowski
Daniel Rikowski

Reputation: 72504

It looks like String.getBytes(Charset charset) is the method you are looking for. It allows you to convert a string into a byte array with the given encoding. (As opposed to String.getBytes() which uses the default encoding)

Your code could be like this:

byte[] myOutput = myString.getBytes(CharsetProvider.charsetForName("UTF-16"));

For details see the Javadocs

Upvotes: 2

Related Questions