Check for a string to be in English using Java
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;
}
}
{
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:
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