How to Write UTF-8 Encoded Data into a File in Java


In this example, we will learn the method to write UTF-8 encoded data into a file in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class FileOperator21Example { 
	public static void main(String[] args )
    {	
		try
        {
        	 File path = new File("example.txt");
        	 if (!path.exists()) 
        	 {
        		 path.createNewFile();
        	 }
        	 
        	 FileOutputStream writerStream = new FileOutputStream(path);
        	 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
             String content =  "testrnwrite";
             writer.write(content);
             writer.close();
 			 System.out.println("Done");
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

Output:

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