Detect non-ASCII characters in string
import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.Arrays; public class Main { public static void main(String[] args) throws Exception { byte[] invalidBytes = " ".getBytes(); byte[] validBytes = "(c)".getBytes(); CharsetDecoder decoder = Charset.forName("US-ASCII").newDecoder(); 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())); } }