FileWriter class in Java
The FileWriter class is used to write the data to a file of a given file name or full path string. The FileWriter class will throw an Exception named IOException or SecurityException so you need to handle the Exception in your code.
Creation of a FileWriter is not dependent on the file already existing. A FileWriter will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown.
There are commonly used constructor
FileWriter(String path of file)
In this constructor you give the path of a specific directory like as "D:\abhishekDubey\java".
FileWriter(String pathoffile, boolean append)
In this constructor there are two arguments, first pathofthefile and second append if append is true then ouput is appended to the end of the file.
FileWriter(File fileobject)
In this constructor you can give the direct File type object that describes the file.
Example
The following example shows how a string can be written to a file with the help of the FileWriterclass; this program first checks the current directory to determine if the particular file is available or not; if not then it creates a new file before writing the data to the file.
- import java.io.*;
- class MyFileWriter {
- public static void main(String arg[]) throws IOException {
- // first we make the object of FileWriter class
- FileWriter fw = new FileWriter("abhishek.txt");
- //this is a string and using write in "abhishek.txt" file
- String s = "this article complete for all of you for learning purpose";
- // toCharArray() is method to convert a string in a character array
- char ch[] = s.toCharArray();
- for (int i = 0; i < ch.length; i++)
- fw.write(ch[i]);
- fw.close();
- }
- }




Join the conversation! Your thoughts help the community grow.