Why does FileReader and FileWriter use an INT
variable to read and write from ?
When reading a text file,should this variable not be of type String or char ?
Why is it INT
?
Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information as these are Byte stream classes. FileWriter.
FileReader is a class in the java.io package which can be used to read a stream of characters from the files. This class uses either specified charset or the platform's default charset for decoding from bytes to characters.
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
If you look at the documentation for InputStreamReader
, you will see that it provides two read()
methods. One returns a single character as an int
and the other reads data into a char[]
. I assume you are asking about the first version. The reason it returns int
rather than char
is so that it can return -1 when the stream reaches EOF.
If you want to read other types of data, such as String
or double
, there are other stream classes which you can wrap around the FileReader
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With