简体   繁体   English

是否可以为UTF-8文件创建InputStream?

[英]Is it possible to create InputStream for a UTF-8 file?

We are making some code change to our production code. 我们正在对生产代码进行一些代码更改。

In this, earlier we used a InputStream (Basically a FileInputStream) for reading a file from file path and this InputStream is passed to many methods ahead. 在本文中,我们之前使用InputStream(基本上是FileInputStream)从文件路径读取文件,并且此InputStream传递给了前面的许多方法。

Now we realized, the file can contain chinese characters also, so we want to use UTF-8 encoding. 现在我们意识到,文件也可以包含汉字,因此我们想使用UTF-8编码。

I have a file path in string. 我有一个字符串文件路径。 And know, sometimes the file can contain chinese character and sometimes not. 并且知道,文件有时可以包含汉字,有时不能包含汉字。

I am reluctant to make changes in so many methods and was trying to somehow use UTF-8 encoding while creating InputStream (FileInputStream). 我不愿意在许多方法中进行更改,并且在创建InputStream(FileInputStream)时试图以某种方式使用UTF-8编码。

I searched on internet but all I could get is output in bufferreader/inputstream reader (like example Reading InputStream as UTF-8 or http://www.mkyong.com/java/how-to-read-utf-8-encoded-data-from-a-file-java/ 我在互联网上进行搜索,但我所能获得的只是在bufferreader / inputstream reader中输出的(例如, 以UTF-8http://www.mkyong.com/java/how-to-read-utf-8-encoded-来自文件Java /的数据

So is it possible to read a file from file path and also handle chinese characters and convert it in InputStram? 那么是否可以从文件路径读取文件并处理汉字并将其转换为InputStram?

An InputStream does not handle text, so it does not care about the encoding, so the direct answer to your question is: no, you can't create an InputStream with UTF-8 encoding. InputStream不处理文本,因此它不关心编码,因此,对您的问题的直接回答是:不,您不能使用UTF-8编码创建InputStream

You can however handle UTF-8 files just fine with an InputStream by simply carrying the bytes around and never manipulating them in any way. 但是,您可以通过使用InputStream来处理UTF-8文件,方法是简单地携带这些字节,而不用任何方式对其进行操作。

If you want to read text from a file you need to construct a Reader and then you'll need to specify the encoding (UTF-8 for you) in the constructor. 如果要从文件读取文本 ,则需要构造一个Reader然后需要在构造函数中指定编码(为您指定UTF-8)。

If you show us the point where data from the InputStream gets turned into String or char[] objects, then I can show you the place where you need to change your code. 如果您向我们展示了InputStream中的数据变成Stringchar[]对象的地步,那么我可以向您展示您需要更改代码的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM