Jump to Real's How-to Main page

Detect non-ASCII character in a String

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharacterCodingException;

public class TestAscii {

  public static void main (String args[])
    throws Exception {
     // this String throws an Exception, it contains an accented letter
     String test = "Réal";
     // this String is OK
     //String test = "Real";

     byte bytearray []  = test.getBytes();
     System.out.println("Test string : " + test);

     CharsetDecoder d = Charset.forName("US-ASCII").newDecoder();
     try {
       CharBuffer r = d.decode(ByteBuffer.wrap(bytearray));
       r.toString();
     }
     catch(CharacterCodingException e) {
       System.out.println("only regular ASCII characters please!");
       // interrupt the processing
       throw new Exception(e);
     }
     System.out.println("Ok, it's ASCII only!");
  }
}
Another way is to use a regular expression, see this Javascript HowTo for a hint!


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2008
[ home ]