We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have a working method to import a string from a UDP packet:
void receive( byte[] data ) { // handler
String message = new String(data);
println(message);
}
While this works, I'd like to make it more robust by specifying the charset of the incoming data (which is ASCII).
Thanks in advance
Answers
http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#String-byte:A-java.nio.charset.Charset-
http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html
So shouldn't it be:
void receive( byte[] data ) { // handler String message = new String(data, Charset US-ASCII); println(message); }
But I get a syntax error...
http://docs.Oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-
I'm afraid I still can't figure it out. Most of what I can find online suggests I don't need the 'Charset' there and instaed should have:
`String message = new String(data, US-ASCII);'
But this gives me an UnsupportedEncodingException
Since I've never even thought about such rare usage, I haven't checked all of the overloaded constructors available for class String.
Actually there are 15 overloaded constructors for it from the link I've passed to ya:
http://docs.Oracle.com/javase/8/docs/api/java/lang/String.html#constructor.summary
And indeed 2 among them accept a String argument for the name of the chosen charset:
However, that approach demands a
try...catch ()
block in order to deal w/ UnsupportedEncodingException:https://Processing.org/reference/try.html
http://docs.oracle.com/javase/8/docs/api/java/io/UnsupportedEncodingException.html
There's no need for such if we use the Charset overload approach though! :-\"
In short, what you had was an "Unhandled exception type".
Which is how the Java compiler "hints" us that it "demands" a
try...catch ()
block there: [-(The same util function if you had used my original tip for Charset + forName(): ;;)
Surprising, you should have a syntax error instead, since US-ASCII isn't a valid Java identifier...
"Most of what I can find online"
They you find mostly outdated information... The constructor with Charset was added with Java 1.6. It is safer to use than the version with String, precisely to avoid this "UnsupportedEncodingException": you can put garbage in a string, but Charset offsets something more type-safe.