Write UTF-8 Encoded Data in java

In this post, we will see how to write UTF-8 Encoded Data.

Sometimes, we have to deal with UTF-8 Encoded Data in our application. It may be due localization or may be processing data from user input.

We will use Hindi language sentences to write in file.

There are three ways to write UTF-8 Encoded Data in Java.
[toc]

Using Files’s newBufferWriter()

We can use java.nio.file.Files's newBufferedWriter() to write UTF8 data to file.

package org.arpit.java2blog;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteUTF8NewBufferWriter {

    public static void main(String[] args) {
        writeUTF8UsingnewBufferWriter();
    }

    // using newBufferedWriter method of java.nio.file.Files
    private static void writeUTF8UsingnewBufferWriter() {
        Path path = FileSystems.getDefault().getPath("/users/apple/WriteUTF8newBufferWriter.txt");

        Charset charset = Charset.forName("UTF-8");

        try {
            BufferedWriter writer = Files.newBufferedWriter(path, charset);
            writer.write("यह फ़ाइल UTF-8 newBufferWriter से लिखी गई है");
            writer.flush();
            writer.close();
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }
}

When you run above program, WriteUTF8newBufferWriter.txt will be created at /users/apple/WriteUTF8newBufferWriter.txt.
Let’s open the file and have a look at content.

WriteUTF-8NewBufferWriter

Using BufferedWriter

We need to pass encoding as UTF8 while creating new OutputStreamWriter.

package org.arpit.java2blog;

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;

public class WriteUTF8DataMain {
    public static void main(String[] args) {
        try {
            File utf8FilePath = new File("/users/apple/UTFDemo.txt");

            Writer writer = new BufferedWriter(new OutputStreamWriter(
                            new FileOutputStream(utf8FilePath), "UTF8"));

            writer.append("UTF-8 Demo for java2blog.com").append("\r\n");
            writer.append("यह हिंदी का वाक्य है").append("\r\n");

            writer.flush();
            writer.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

When you run above program, UTFDemo.txt will be created at /users/apple/UTFDemo.txt.
Let’s open the file and have a look at content.

UTFDemo

Using DataOutputStream’s writeUTF() method

We can use DataOutputStream's writeUTF() to write UTF8 data to file.

package org.arpit.java2blog;

import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteUTFMain {

    public static void main(String[] args) {
        try { 
        FileOutputStream fos = new FileOutputStream("/users/apple/WriteUTFDemo.txt");
         DataOutputStream dos = new DataOutputStream(fos);
         dos.writeUTF("आप कैसे हैं");
         dos.close();
        }
        catch(EOFException ex) {
             System.out.println(ex.toString());
          }
          catch(IOException ex) {
             System.out.println(ex.toString());
          }
    }
}

Output:

WeiteUTFDemo

When you run above program, WriteUTFDemo.txt will be created at /users/apple/WriteUTFDemo.txt.
That’s all about how to write UTF-8 Encoded Data in java

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.