FileWriter in java
In previous post, we have seen InputStream and OutputStream. In this post, we will see how to write data to a text file with the help of FileWriter in java.
FileWriter is a character based classes unlike FileOutputStream which is used for writing byte based data.
In other words, we should use FileWriter class when the data is in textual form.
Let’s understand it with example.
FileWriter:
FileWriter is used to write a stream of characters to a file.
Constructor of the FileWriter:
Constructor | Description |
FileWriter(String file) | Creates a new File.It gets the file name in the String. |
FileWriter(File file) | Creates a new File. It gets the file name in the File Object. |
Example of FileWriter:
public static void main(String[] args){ try{ FileWriter fw=new FileWriter("Sample.txt"); fw.write("FileWriter example in testingpool"); fw.close(); }catch(Exception e){ System.out.println(e); } System.out.println("Write successfully"); } }
FileWriter Methods:
- public void write(String text) : It writes String into FileWriter.
- public void write(char c) : It writes the char into FileWrite.
- public void write(char[] c) : It writes char array into FileWriter.
- public void flush() : It flushes the data of FileWriter.
- public void close() : It closes FileWriter.
Overwriting and Appending the File:
When creating FileWriter, we can decide if we want to overwrite the existing file with same name or we want to append the existing file with the data. For that , we have 2 provide a boolean parameter. Let’s see how to do this.
FileWriter writer = new FileWriter("D:\\Mydata\\Sample.txt", true); //appends to file FileWriter writer = new FileWriter("D:\\Mydata\\output.txt", false); //overwrites file
In the next post, we will see FileReader which is used for reading data from a text file.
1 Response
[…] For writing character oriented data, we can use FileWriter. […]