Groovy web console

subscribe to the feed Subscribe
to this
site

UTF-8 validation

Published 2 years ago by vmj with tags utf-8 validation
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
import java.nio.ByteBuffer
import java.nio.charset.CharacterCodingException

import static java.nio.charset.StandardCharsets.UTF_8

final s = [0xff] as byte[]
boolean b = false

try {
    UTF_8.newDecoder().decode(ByteBuffer.wrap(s))
    b = true
} catch (CharacterCodingException e) {
    b = false
}

println "s is valid UTF-8: $b"