FileReader rd=new FileReader("new.mp4");
FileWriter wr=new FileWriter("output.mp4");
int ch;
while((ch=rd.read())!=-1)
wr.write(ch);
wr.flush();
wr.close();
When I use the FileReader
and FileWriter
to read and write an mp4 file, the output.mp4
file can't be rendered well. But when I use FileInputStream
and FileOutputStream
instead it worked well.
So can I conclude FileReader
and FileWriter
are only for reading and writing text?
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 charactersThe difference between
FileInputStream
andFileReader
is,FileInputStream
reads the file byte by byte andFileReader
reads the file character by character.So when you are trying to read the file which contains the character
"Č"
, inFileInputStream
will give the result as196 140
, because theASCII
value ofČ
is268
.In
FileReader
will give the result as268
which is theASCII
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
Yes, your conclusion is correct subclasses of
Reader
andWriter
are for reading/writing text content.InputStream
/OutputStream
are for binary content. If you take a look at the documentation:FileReader
(and indeed anything extending Reader) is indeed for text. From the documentation ofReader
:(Emphasis mine.) Look at the API and you'll see it's all to do with text -
char
instead ofbyte
all over the place.InputStream
andOutputStream
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, useInputStreamReader
around aFileInputStream
... 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
andwrite
which read into or write from a buffer - either abyte[]
or achar[]
. 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.A text file can be read using both
fileReader
andfileInputStream
but mp3 and png can only be read usingfileInputStream
fileReader
reads char by charfileInputStream
reads byte by byte