Java FileWriter and FileReader classes are used to write and read data from text files. These are character-oriented classes, used for file handling in java.
Java has suggested not to use the FileInputStream and FileOutputStream classes if you have to read and write the textual information.
Java FileWriter class
Java FileWriter class is used to write character-oriented data to the file.
Constructors of FileWriter class
Constructor | Description |
---|---|
FileWriter(String file) | creates a new file. It gets file name in string. |
FileWriter(File file) | creates a new file. It gets file name in File object. |
Methods of FileWriter class
Method | Description |
---|---|
1) public void write(String text) | writes the string into FileWriter. |
2) public void write(char c) | writes the char into FileWriter. |
3) public void write(char[] c) | writes char array into FileWriter. |
4) public void flush() | flushes the data of FileWriter. |
5) public void close() | closes FileWriter. |
Java FileWriter Example
In this example, we are writing the data in the file abc.txt.
Output:
success...
Java FileReader class
Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
Constructors of FileWriter class
Constructor | Description |
---|---|
FileReader(String file) | It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. |
FileReader(File file) | It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. |
Methods of FileReader class
Method | Description |
---|---|
1) public int read() | returns a character in ASCII form. It returns -1 at the end of file. |
2) public void close() | closes FileReader. |
Java FileReader Example
In this example, we are reading the data from the file abc.txt file.
Output:
my name is sachin
No comments:
Post a Comment