The article is about the File Handling in Java.
Before we begin, know that there are many different classes in Java related to File Handling. They have a lot in common aside from a few differences so the concept remains roughly the same. Some of these Classes are File, FileResource, FileReader, FileWriter, FileOutputStream, FileInputStream, BufferedWriter and BufferedReader.
Typically anything with Input or Reader is used to read data from files, whereas anything with Output or Writer is used to write data to files. In this article, we’ll cover File, FileWriter and FileReader.
FileWriter
The FileWriter class is used to write data in the form of text to text files. It writes a stream of characters to the file, as compared to the stream of bytes that the FileOutputStream class writes.
Before we use any of the methods in the FileWriter class, we must declare an object for it.
FileWriter obj = new FileWriter(file_path)- obj is the name of the object which we creating from the FileReader Class.
- The new keyword is used to create the object from the FileReader Class.
- The file_path must be a string and a valid path to a text file on your computer.
In the code below we are going to write to a file called “Data.txt”. If this file does not already exist, the FileWriter Class is create it for you.
Remember to import the two following classes into your code as they are not included normally. Secondly, remember to include the throws IOException statement. It’s part of Java’s behavior to throw an IO exception when reading or writing. Finally, it’s the write() function that we use to insert text into the file.
import java.io.FileWriter;
import java.io.IOException;
public class example {
public static void main(String[] args) throws IOException {
FileWriter file = new FileWriter("C://CodersLegacy/Data.txt");
String data;
data = "File Handling in Java - CodersLegacy";
file.write(data);
file.close();
}
}
Below is a screenshot of the text file created by the above code. If a file with this name had already existed, any data in it would have been wiped and overwritten with the below text.
