Write to file in java code by using FileOutputStream and BufferedWriter classes.
 
Create FileOutputStream object by passing absolute path of the file.
 
Create OutputStreamWriter object by passing outputStream and also optionally you can specify character set (utf-8 used here).

 OutputStream outputStream = new FileOutputStream(filename);
 OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream,"utf-8");

 
Create BufferedWriter object and use writer.write() method for writing any string.

Writer writer = new BufferedWriter(streamWriter);
writer.write("Hello digital app consultancy");

 
Complete class WriteFile.java can be found below;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class WriteFile {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		writeFile("C:/temp/fileName.txt");
	}

	 public static void writeFile(String filename) 
	    {
		 	Writer writer = null;
	        System.out.println("Writing File from Java code");
	           try{
	        	   
	              OutputStream outputStream = new FileOutputStream(filename);
	              OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream,"utf-8");

	              //Instantiate the BufferedWriter Class
	              writer = new BufferedWriter(streamWriter);
	              
	              // Writing a line using write method.
	              writer.write("Hello digital app consultancy");
	              
	           }catch (Exception e) {
	            e.printStackTrace();
	           }finally{
	        	   try {writer.close();} catch (Exception ex) {/*ignore*/}
	           }
	    }
}

 
For further reading refer Java Programming Category posts.

Share this post

How to write to file in java code
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *