FileInputStream vs FileReader

笑着哭i 提交于 2019-11-27 00:27:13

Yes, your conclusion is correct subclasses of Reader and Writer are for reading/writing text content. InputStream / OutputStream are for binary content. If you take a look at the documentation:

Reader - Abstract class for reading character streams

InputStream - Abstract class is the superclass of all classes representing an input stream of bytes.

FileReader (and indeed anything extending Reader) is indeed for text. From the documentation of Reader:

Abstract class for reading character streams.

(Emphasis mine.) Look at the API and you'll see it's all to do with text - char instead of byte all over the place.

InputStream and OutputStream are for binary data, such as mp4 files.

Personally I would avoid FileReader altogether though, as it always uses the system default character encoding. Instead, use InputStreamReader around a FileInputStream... but only when you want to deal with text.

As an aside, that's a very inefficient way of copying from an input to an output... use the overloads of read and write which read into or write from a buffer - either a byte[] or a char[]. Otherwise you're calling read and write for every single byte/character in the file.

You should also close IO streams in finally blocks so they're closed even if an exception is thrown while you're processing them.

satender

FileInputStream is used for reading streams of raw bytes of data, like raw images. FileReaders, on the other hand, are used for reading streams of characters

The difference between FileInputStream and FileReader is, FileInputStream reads the file byte by byte and FileReader reads the file character by character.

So when you are trying to read the file which contains the character "Č", in FileInputStream will give the result as 196 140, because the ASCII value of Č is 268.

In FileReader will give the result as 268 which is the ASCII value of the char Č.

"FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream."

http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileWriter.html

FileWriter and FileReader are desinged for Streams of chars...

best regards.

Furkan

IshanGarg

A text file can be read using both fileReader and fileInputStream but mp3 and png can only be read using fileInputStream

  1. fileReader reads char by char

  2. fileInputStream reads byte by byte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!