Java FileReader Class
The FileReader class inherits from the InputStreamReader class. This class reads data from a stream character by character. You can create the needed object using the following constructors.
Creates a new FileReader given the File from which to read data.
FileReader(File file)
Creates a new FileReader given the FileDescriptor from which to read data.
FileReader(FileDescriptor fd)
Creates a new FileReader given the file name from which to read data.
FileReader(String fileName)
After successfully creating a FileReader object, you can operate on the file using the methods in the following list.
| No. | File description |
|---|---|
| 1 | public int read() throws IOException |
| Reads a single character and returns an int variable representing the character read | |
| 2 | public int read(char [] c, int offset, int len) |
| Reads characters into the array c and returns the number of characters read |
Example
Example
import
java
.
io
.*;
public
class
FileRead
{
public
static
void
main
(
String
args
[
]
)
throws
IOException
{
File
file
=
new
File
(
"
Hello1.txt
"
)
;
//
Create a file
file
.
createNewFile
(
)
;
//
creates a FileWriter Object
FileWriter
writer
=
new
FileWriter
(
file
)
;
//
Write content to the file
writer
.
write
(
"
This
\n
is
\n
an
\n
example
\n
"
)
;
writer
.
flush
(
)
;
writer
.
close
(
)
;
//
Create a FileReader object
FileReader
fr
=
new
FileReader
(
file
)
;
char
[
]
a
=
new
char
[
50
]
;
fr
.
read
(
a
)
;
//
Read the contents of the array
for
(
char
c
:
a
)
System
.
out
.
(
c
)
;
//
Print characters one by one
fr
.
close
(
)
;
}
}
The compilation and execution results of the above example are as follows:
This
is
an
example
Java Stream