How to detect non-ASCII characters in string?

Below java shows how to detect non-ASCII characters in a String –

 * Created on 03-2012 Copyright(c) All Rights Reserved.
package com.kodehelp.javaio;

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

 * Created by
 * Date: 3/18/12
public class FindNonAsciiCharacters {
    public static void main(String[] args) {

        byte[] invalidBytes = "Copyright © 2009-2012".getBytes();
        byte[] validBytes = "Copyright (c) 2009-2012".getBytes();

        CharsetDecoder decoder = Charset.forName("US-ASCII").newDecoder();
        try {
            CharBuffer buffer = decoder.decode(ByteBuffer.wrap(validBytes));

            buffer = decoder.decode(ByteBuffer.wrap(invalidBytes));
        } catch (CharacterCodingException e) {
            System.err.println("The information contains a non ASCII character(s).");

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.