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");  
			 } 
	}
Output: Write successfully

FileWriter Methods:

  1. public void write(String text) : It writes String into FileWriter.
  2. public void write(char c) : It writes the char into FileWrite.
  3. public void write(char[] c) : It writes char array into FileWriter.
  4. public void flush() : It flushes the data of FileWriter.
  5. 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.

Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 8, 2015

    […] For writing character oriented data, we can use FileWriter. […]