21

I am using getResourceAsStream to access a local file. What encoding does it assume the file is?

Casebash
  • 114,675
  • 90
  • 247
  • 350

2 Answers2

48

InputStreams don't have encodings. They're just streams of bytes. Readers are for text with an encoding. You can create a Reader with a specific charset from an InputStream like this:

Reader reader = new InputStreamReader(inputStream, "UTF-8");

If you're using a charset that's guaranteed to be supported on all Java platforms like UTF-8, you can avoid having to deal with impossible UnsupportedEncodingExceptions by using a constant from Guava's Charsets class like Charsets.UTF_8.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • 2
    Why do you need Guava for that? – Casebash Apr 08 '11 at 06:19
  • 1
    @Casebash: I just mentioned Guava because it makes working with charsets a bit more convenient. You don't need Guava to use readers or charsets (though it does have some awesome utilities for making things easier beyond what I mentioned here). – ColinD Apr 08 '11 at 13:23
  • 4
    Since Java 1.7, you can use `StandardCharsets.UTF_8.name()` to get the "UTF-8" constant. – LaurentG Oct 16 '17 at 07:39
  • 1
    @LaurentG: But there shouldn't generally be any need to actually get the name... most APIs (such as `InputStreamReader`) that could take a `String` for the charset name should also have a version that takes a `Charset` directly. – ColinD Oct 17 '17 at 15:56
1

I do not know how to use encoding in getResourceStream(), generally you can query the file.encoding property or Charset.defaultCharset() to find the current default encoding.it is better to explicitly specify the desired encoding (i.e. "UTF-8") in the code. In this way, it will work even across different platforms.

Also how to read a file , you can look at this post How to create a Java String from the contents of a file Jon Skeet's answer.

Community
  • 1
  • 1
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112