Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does FileReader and FileWriter use an INT variable to read and write from?

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?

like image 584
user3274549 Avatar asked Sep 08 '14 09:09

user3274549


People also ask

What is FileReader and FileWriter?

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.

How does FileReader work java?

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.

What classes do you use to read data from a file?

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.


1 Answers

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.

like image 141
Code-Apprentice Avatar answered Oct 26 '22 15:10

Code-Apprentice