Writing a file refers to writing some data to a file. Java provides the FileWriter class, which helps write data to files.
Following are the two ways to create FileWriter class object.
FileWriter file = new FileWriter("Path/file");
//Supposing we have created a file class object as fileObj;
FileWriter file = new FileWriter(File fileObj);
Note :
If the file is not already created, the FileWriter class object is able to create a new text file and then writes data.
writingFile.java :
import java.io.FileWriter;//importing FileWriter class
public class writingFile
{
public static void main(String[] args) throws Exception {
//Creating a fileWriter object with specified directory and file name;
FileWriter writefile = new FileWriter("shiva.txt");
//FileWriter writefile = new FileWriter(File fileObj);
//we can use this if text file is created with fileOjb
//writing data to file using write() method.
writefile.write("Writing data in file is very simple task !");
writefile.close();
System.out.println("Writing a file successfully completed!");
//closing file.
}
}
Output :
Writing a file successfully completed !
Note : – When you are done writing to the file, you should close it with the close() method.