Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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 it would be much better to refer to some static final variable instead. Do you know where I can find such a variable in JDK?

BTW, on second thought, such constants are bad design: Public Static Literals ... Are Not a Solution for Data Duplication

1 Answer

0 votes
by (46k points)

In Java 1.7 and above, you can use java.nio.charset.StandardCharsets to define constants for Charset including UTF_8.

import java.nio.charset.StandardCharsets;

...

StandardCharsets.UTF_8.name();

Related questions

0 votes
1 answer
asked Nov 26, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...