Reputation: 13108
I have read this oracle java tutorial, which basically shows that you can copy a txt file either by using a FileInputStream
or a FileReader
. Although they recommend using the latter approach I have a question about.
I would like to know what happens in using the first approach using a FileInputStream which basically reads plain raw bytes.
from this link:
public class FileInputStream extends InputStream
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
If it's meant to be reading only raw bytes and there is no InputFileReader
which bridges byte into chars. How come that by only using FileInputStream
, it still works?
Upvotes: 2
Views: 1377
Reputation: 545
A FileInputStream could be a Stream of Bytes from any File, e.g. a mp3 File: Its just the answer on "how do i get any file into my java runtime?". The FileReader is ment for use with character Files like .txt formats. Ofcourse you can also use it with any file, but as you read characters with a FileReader you may run in coding errors. Remember bytes are encoded utf8 default characters are ascii.
Upvotes: 1
Reputation: 4093
I'm not quite sure what you are asking but I think what you are looking for is InputStreamReader
(link) which is used to convert a stream of bytes into characters. Care needs to be taken when converting byte streams into character streams as unicode can (and often does) use more than one byte per character.
Upvotes: 1
Reputation: 9954
As you pointed out a FileInputStream
(or generally an InputStream
is for reading raw data as bytes whereas a FileReader
( or generally a Reader
) is for reading character data.
The Reader
will translate read bytes into charcters for you. A Reader
will either use the default platform encoding or the encoding given in the constructor for this translation.
Copying a text file with a FileInputStream
works because on the disk even a text file only consists of bytes.
Upvotes: 3