Advertisement



< Prev
Next >



FileWriter



FileWriter class is a subclass of Writer abstract class and it is used to write a character, character array or a String to a file.




FileWriter Constructor:


FileWriter(File file)
This constructor creates a FileWriter object to write characters to a file referenced by a File object.
Example-:
File file = new File("D:\\Textbook.txt");
FileWriter fr = new FileWriter(file);





Methods for writing using FileWriter


Some methods that we generally use while working with FileWriter are shown in the table below :

Methods Description
flush()
This method flushes any buffered data to be written out of this character output stream.
write(int c)
This method writes one character at a time to this character output stream.

write(char[])
This method writes a whole character array at a time to this character output stream.

write(String str)
This method writes a String to this character output stream.

close()
This method closes this output stream and also frees any resources connected with this output stream.




Advertisement




Writing a character array and a String to a file using FileWriter class.


Writing to a file TextBook.txt using its path D:\\TextBook.txt.
import java.io.*;
class A
{
public static void main(String... ar)
{
char[] arr= {'H', 'e', 'l' , 'l' , 'o', '-'};
String str="How are you today?";

try
{
File file= new File("D:\\TextBook.txt");
FileWriter fw= new FileWriter(file); // This will create the file and we don't need to call createNewFile();

for(char ch : arr) //For-each loop to write each character to a file
fw.write(ch);

fw.write(str); //Writing a String to a file

fw.flush();
fw.close();
}
catch(IOException e)
{
System.out.println(e);
}

}
}



Output is -:


After the execution of this program, a file "TextBook.txt" is created in the D: drive, with contents -:
Hello-How are you today?


Program Analysis






Please share this article -




< Prev
Next >
< FileReader
BufferedReader >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement