How to Write UTF-8 Data into a File Using Java ?

DeeKay June 10, 2012 at 2:22 am · java.io

Below Java Code shows how to write UTF-8 encoded data into a text file –

/****************************************************************************************
 * Created on 06-2012 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

/**
 * Created by http://kodehelp.com
 * Date: 6/9/12
 */
public class WriteUTF8DataToFile {
    public static void main(String args[]){
        try {
            File fileDir = new File("c:\\Sample.txt");

            Writer out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(fileDir), "UTF8"));

            out.append("kodehelp UTF-8").append("\r\n");
            out.append("??? UTF-8").append("\r\n");
            out.append("???? UTF-8").append("\r\n");

            out.flush();
            out.close();

        }catch (UnsupportedEncodingException e){
            System.out.println(e.getMessage());
        }catch (IOException e){
            System.out.println(e.getMessage());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}