Your daily dose of Java and related technologies.
News, Releases, Reviews, Tutorials, Articles, Events, Contests, Comments, Code and much more.
This java weblog is maintained by Xyling Technologies, making life simpler.

Wednesday, September 26, 2007

Check for a string to be in English using Java


This is useful especially if you are insanely bugged by the smart testers who love international characters being filled at the places where it is not required.

Here is the simple checking code. As always, if you have something better to share, please use comments.


public static boolean canEncode(String s, String cs)
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(baos, cs);
w.write(s);
w.close();
String t = baos.toString(cs);
return s.equals(t);
}
catch(Exception e)
{
return false;
}
}

1 Comments:

Anonymous Laurence Vanhelsuwe said...

Hi, a few non-functional bits of feedback, if that's OK too.. catch Exception is a big no-no. Such a catch also catches NullPointerException, IllegalArgumentException, and every other runtime exception. This is almost never what you intend. Most likely you intended to only catch IOException.

Secondly, your parameter and local variable names are poor. To cap it, there's no javadoc, so most of your readers will have no clue what 'cs' is supposed to contain, without delving into javadocs for stuff your logic uses...

3:22 PM

 

Post a Comment

<< Home