How to detect non-ASCII characters in string?

DeeKay April 6, 2012 at 1:51 am · java.nio

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

/****************************************************************************************
 * Created on 03-2012 Copyright(c) http://kodehelp.com 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 http://kodehelp.com
 * Date: 3/18/12
 */
public class FindNonAsciiCharacters {
    public static void main(String[] args) {

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


        CharsetDecoder decoder = Charset.forName("US-ASCII").newDecoder();
        try {
            CharBuffer buffer = decoder.decode(ByteBuffer.wrap(validBytes));
            System.out.println(Arrays.toString(buffer.array()));

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