HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

894@Where to get "UTF-8" string literal in Java?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
literaljavawhere894stringutfget

Problem

I'm trying to use a constant instead of a string literal in this piece of code:

new InputStreamReader(new FileInputStream(file), "UTF-8")


"UTF-8" appears in the code rather often, and would be much better to refer to some static final variable instead. Do you know where I can find such a variable in JDK?

Solution

In Java 1.7+, the class java.nio.charset.StandardCharsets defines constants for Charset including UTF_8.

import java.nio.charset.StandardCharsets;

...

StandardCharsets.UTF_8.name();


For Android: minSdk 19

Code Snippets

import java.nio.charset.StandardCharsets;

...

StandardCharsets.UTF_8.name();

Context

Stack Overflow Q#6698354, score: 1003

Revisions (0)

No revisions yet.