HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Read Write UTF-8 Encoded File

Java Read Write UTF-8 Encoded File

Many times we need to deal with the UTF-8 encoded file in our application. This may be due to localization needs or simply processing user input out of some requirements.

Even some data sources may provide data in UTF-8 format only. In this Java tutorial, we will learn two very simple examples of reading and writing UTF-8 content from a file.

1. Writing UTF-8 Encoded Data into a File

The given below is a Java example to demonstrate how to write “UTF-8” encoded data into a file. It uses the character encoding “UTF-8” while creating the OutputStreamWriter.

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;
import java.nio.charset.StandardCharsets;

public class WriteUTF8Data
{
   public static void main(String[] args)
   {
      try
      {
         File fileDir = new File("c:\\temp\\test.txt");

         Writer out = new BufferedWriter(new OutputStreamWriter
                           (new FileOutputStream(fileDir), StandardCharsets.UTF_8));

         out.append("Howtodoinjava.com").append("\r\n");
         out.append("UTF-8 Demo").append("\r\n");
         out.append("क्षेत्रफल = लंबाई * चौड़ाई").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());
      }
   }
}
You need to enable the Eclipse IDE for support of the UTF-8 character set before running the example in Eclipse. By default, it is disabled. If you wish to enable the UTF-8 support in eclipse, you will get the necessary help for my previous post:

How to compile and run java program written in another language

2. Reading UTF-8 Encoded File

We need to pass StandardCharsets.UTF_8 into the InputStreamReader constructor to read data from a UTF-8 encoded file.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class ReadUTF8Data
{
   public static void main(String[] args)
   {
      try {
         File fileDir = new File("c:\\temp\\test.txt");
  
         BufferedReader in = new BufferedReader(
            new InputStreamReader(
                       new FileInputStream(fileDir), "UTF8"));
  
         String str;
  
         while ((str = in.readLine()) != null) {
             System.out.println(str);
         }
  
                 in.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());
         }
   }
}

Program Output:

Howtodoinjava.com
UTF-8 Demo
क्षेत्रफल = लंबाई * चौड़ाई

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Rakhi

    March 5, 2015

    instead of giving output क्षेत्रफल = लंबाई * चौड़ाई it is giving ????=???? * ???. how to overcome this error?

    • Lokesh Gupta

      March 5, 2015

      Follow the instruction giver here.

  2. Shivam

    November 6, 2014

    Hi Lokesh,

    My question is somewhat different from this post.
    How to escape accented characters(it may include UTF-8, UTF-16…) apart from using apache commans.lang library.

    Thanks in advance.

    Regards,

    • Lokesh Gupta

      November 6, 2014

      Normalizer.normalize(string, Normalizer.Form.NFD);

      Read more: https://stackoverflow.com/questions/3322152/is-there-a-way-to-get-rid-of-accents-and-convert-a-whole-string-to-regular-lette

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces