java getResourceAsStream - 它读作什么编码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5590451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getResourceAsStream - What encoding is it read as?
提问by Casebash
I am using getResourceAsStreamto access a local file. What encoding does it assume the file is?
我正在使用getResourceAsStream访问本地文件。它假设文件是什么编码?
回答by ColinD
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:
InputStream
s 没有编码。它们只是字节流。Reader用于带有编码的文本。您可以Reader
从InputStream
这样的特定字符集创建一个:
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
.
如果您使用有保证的所有Java平台,如UTF-8将要支持的字符集,你可不必处理不可能UnsupportedEncodingException
通过利用从常数s番石榴的Charsets
象类Charsets.UTF_8
。
回答by Dead Programmer
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.
我不知道如何在 中使用编码getResourceStream()
,一般可以查询file.encoding
属性或Charset.defaultCharset()
查找当前默认编码。最好在代码中明确指定所需的编码(即“UTF-8”)。这样,它甚至可以跨不同平台工作。
Also how to read a file , you can look at this post How to create a Java String from the contents of a fileJon Skeet's answer.
还有如何读取文件,您可以查看这篇文章 如何从文件内容创建 Java 字符串Jon Skeet 的回答。