I\'m trying to use a constant instead of a string literal in this piece of code:
new InputStreamReader(new FileInputStream(file), \"UTF-8\")
<
You can use Charset.defaultCharset()
API or file.encoding
property.
But if you want your own constant, you'll need to define it yourself.
The Google Guava library (which I'd highly recommend anyway, if you're doing work in Java) has a Charsets class with static fields like Charsets.UTF_8
, Charsets.UTF_16
, etc.
Since Java 7 you should just use java.nio.charset.StandardCharsets
instead for comparable constants.
Note that these constants aren't strings, they're actual Charset
instances. All standard APIs that take a charset name also have an overload that take a Charset
object which you should use instead.
If you are using OkHttp for Java/Android you can use the following constant:
import com.squareup.okhttp.internal.Util;
Util.UTF_8; // Charset
Util.UTF_8.name(); // String
Class org.apache.commons.lang3.CharEncoding.UTF_8
is deprecated after Java 7 introduced java.nio.charset.StandardCharsets
In Java 1.7+, java.nio.charset.StandardCharsets defines constants for Charset
including UTF_8
.
import java.nio.charset.StandardCharsets;
...
StandardCharsets.UTF_8.name();
For Android: minSdk 19
Constant definitions for the standard. These charsets are guaranteed to be available on every implementation of the Java platform. since 1.7
package java.nio.charset;
Charset utf8 = StandardCharsets.UTF_8;