How to Write to File in Java


This example demonstrates how to write to file in Java.

Source Code

1) Using java.io.FileOutputStream

package com.beginner.examples;

import java.io.*;

public class FileOperator6Example { 
	public static void main(String[] args )
    {	
		try
        {
        	 File path = new File("example.txt");
        	 if (!path.exists()) 
        	 {
        		 path.createNewFile();
        	 }
        	 
             FileOutputStream fo = new FileOutputStream(path);
             String content =  "testrnwrite";
             byte[] cb = content.getBytes();
             fo.write(cb);
             fo.flush();
 			 fo.close();
 			 System.out.println("Done");
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

Output:

Done

2) Using java.io.BufferedWriter

package com.beginner.examples;

import java.io.*;

public class FileOperator7Example { 
	public static void main(String[] args )
    {	
		try
        {
        	 File path = new File("example.txt");
        	 if (!path.exists()) 
        	 {
        		 path.createNewFile();
        	 }
        	 
             FileWriter writer = new FileWriter(path);
             BufferedWriter bw = new BufferedWriter(writer);  
             bw.write("testrnwrite");
             bw.flush();
             bw.close();
             System.out.println("Done");
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

Output:

Done
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments