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.

Using Files’s newBufferWriter()

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

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.

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.

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

Was this post helpful?

Leave a Reply

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