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 data into a file using Java –

<br />
/****************************************************************************************<br />
 * Created on 06-2012 Copyright(c) http://kodehelp.com All Rights Reserved.<br />
 ****************************************************************************************/<br />
package com.kodehelp.javaio;</p>
<p>import java.io.BufferedWriter;<br />
import java.io.File;<br />
import java.io.FileOutputStream;<br />
import java.io.IOException;<br />
import java.io.OutputStreamWriter;<br />
import java.io.UnsupportedEncodingException;<br />
import java.io.Writer;</p>
<p>/**<br />
 * Created by http://kodehelp.com<br />
 * Date: 6/9/12<br />
 */<br />
public class WriteUTF8DataToFile {<br />
    public static void main(String args[]){<br />
        try {<br />
            File fileDir = new File("c:\\Sample.txt");</p>
<p>            Writer out = new BufferedWriter(new OutputStreamWriter(<br />
                    new FileOutputStream(fileDir), "UTF8"));</p>
<p>            out.append("kodehelp UTF-8").append("\r\n");<br />
            out.append("??? UTF-8").append("\r\n");<br />
            out.append("???? UTF-8").append("\r\n");</p>
<p>            out.flush();<br />
            out.close();</p>
<p>        }catch (UnsupportedEncodingException e){<br />
            System.out.println(e.getMessage());<br />
        }catch (IOException e){<br />
            System.out.println(e.getMessage());<br />
        }catch (Exception e){<br />
            System.out.println(e.getMessage());<br />
        }<br />
    }<br />
}<br />