getResourceAsStream - What encoding is it read as?
I am using开发者_开发技巧 getResourceAsStream to access a local file. What encoding does it assume the file is?
InputStream
s 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 UnsupportedEncodingException
s by using a constant from Guava's Charsets
class like Charsets.UTF_8
.
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.
精彩评论