Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Magic with Merlin: Character sets

Conversions and encoding schemes

John Zukowski (jaz@zukowski.net), President, JZ Ventures, Inc.
Author photo
John Zukowski conducts strategic Java consulting with JZ Ventures, Inc. and serves as the resident guru for a number of jGuru's community-driven Java FAQs. His latest books are Learn Java with JBuilder 6 from Apress and Mastering Java 2: J2SE 1.4 from Sybex. Reach him at jaz@zukowski.net.

Summary:  Three classes in the java.nio.charset package help convert between character sets when moving legacy applications to the Java platform. John Zukowski walks you through these classes and provides an example that demonstrates the features.

View more content in this series

Date:  01 Oct 2002
Level:  Introductory

Comments:  

By the numbers

At the risk of stating the obvious, computers only understand numbers. What's perhaps less obvious, however, is that because they only understand numbers, computers need to use some form of mapping of numerical values to corresponding characters so that they can display text. It is these mappings (or character sets) that permit the computer to understand text. For instance, early desktop computers used ASCII for just such a mapping. When a computer that uses ASCII stores the numbers 72, 101, 108, and 112, it knows to display the word "Help," because in ASCII the number 72 is the value of H, 101 is e, 108 is l, and 112 is p. If, however, that computer was an early IBM mainframe using EBCDIC (rather than ASCII), the word "Help" would have been represented by the numbers 200, 133, 147, and 151.


Character set basics

Moving to the Java language, there are three classes in the java.nio.charset package to help with the mappings: Charset, CharsetEncoder, and CharsetDecoder. These classes work together so that you can take one mapping and convert it to another. In the case of going from another mapping to the Java mapping (Unicode), you use a decoder. Then, if you need to go from the Java mapping (Unicode) to a different mapping (or back to the original), you use an encoder. You can't convert directly between two non-Unicode formats with the java.nio.charset package, but by going through an intermediate Unicode format you can convert between two non-Unicode formats.

Before you can get a decoder or encoder, you need to get the Charset for the specific mapping. For instance, US-ASCII is the name of the mapping for the 7-bit ASCII character set. All you need to do is pass that name into the forName() method of Charset as shown here:

Charset charset = 
  Charset.forName("US-ASCII");

Once you have the Charset, just ask for CharsetDecoder and CharsetEncoder:

CharsetDecoder decoder =
  charset.newDecoder();
CharsetEncoder encoder =  
  charset.newEncoder();

After you have the decoder and encoder, you can then convert between the different character sets, as shown below:

  ByteBuffer bytes = ...;
  CharBuffer chars = decoder.decode(bytes);
  bytes = encoder.encode(chars);

Of course, if you aren't sure which character sets are available, you need to ask:

SortedMap map = 
   Charset.availableCharsets();

You would then use a specific decoder to go from external bytes to internal characters. Then, if you needed to send data out of the Java code, you'd use the encoder to go from internal characters to external bytes. As far as which specific character sets are available, your runtime determines the complete set. Every Java programming implementation, however, must support the following encodings:

  • US-ASCII: 7-bit ASCII
  • ISO-8859-1: ISO Latin alphabet
  • UTF-8: 8-bit UCS Transformation Format
  • UTF-16BE: 16-bit UCS Transformation Format, big-endian byte order
  • UTF-16LE: 16-bit UCS Transformation Format, little-endian byte order
  • UTF-16: 16-bit UCS Transformation Format, byte order identified by marker

Different platforms may then support additional character sets specific to that platform (for instance, on Windows platforms, you'll find a Windows-1252 character set supported). If you need support for other sets, you can create your own. See the CharsetProvider API in the java.nio.charset.spi package.


Complete example

Listing 1 demonstrates the Java character set conversion features by converting the ASCII byte array values for the word "Help" (72, 101, 108, and 112). Unfortunately, there is no EBCDIC encoder by default, so we'll convert the value to a UTF-16LE byte array (which just adds in a "0" byte for the second byte of each character).

import java.nio.*;
import java.nio.charset.*;
import java.util.Arrays;

public class Convert {
  public static void main(String args[]) {
    System.out.println(Charset.availableCharsets());
    Charset asciiCharset = Charset.forName("US-ASCII");
    CharsetDecoder decoder = asciiCharset.newDecoder();
    byte help[] = {72, 101, 108, 112};
    ByteBuffer asciiBytes = ByteBuffer.wrap(help);
    CharBuffer helpChars = null;
    try {
      helpChars = decoder.decode(asciiBytes);
    } catch (CharacterCodingException e) {
      System.err.println("Error decoding");
      System.exit(-1);
    }
    System.out.println(helpChars);
    Charset utfCharset = Charset.forName("UTF-16LE");
    CharsetEncoder encoder = utfCharset.newEncoder();
    ByteBuffer utfBytes = null;
    try {
      utfBytes = encoder.encode(helpChars);
    } catch (CharacterCodingException e) {
      System.err.println("Error encoding");
      System.exit(-1);
    }
    byte newHelp[] = utfBytes.array();
    for (int i=0, n=newHelp.length; i<n; i++) {
      System.out.println(i + " :" + newHelp[i]);
    }
  }
}

Note: Besides manually performing the encoding and decoding, you can also provide a Charset to the java.ioInputStreamReader and java.ioOutputStreamWriter constructors and let them do the conversion for you.



Download

NameSizeDownload method
j-mer1022.zip1KBHTTP

Information about download methods


Resources

About the author

Author photo

John Zukowski conducts strategic Java consulting with JZ Ventures, Inc. and serves as the resident guru for a number of jGuru's community-driven Java FAQs. His latest books are Learn Java with JBuilder 6 from Apress and Mastering Java 2: J2SE 1.4 from Sybex. Reach him at jaz@zukowski.net.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


Forgot your IBM ID?


Forgot your password?
Change your password


By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)


By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=10715
ArticleTitle=Magic with Merlin: Character sets
publish-date=10012002
author1-email=jaz@zukowski.net
author1-email-cc=jaloi@us.ibm.com

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).