简体   繁体   中英

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.

Now we realized, the file can contain chinese characters also, so we want to use UTF-8 encoding.

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).

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/

So is it possible to read a file from file path and also handle chinese characters and convert it in 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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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