Write a UTF-8 file with Java using OutputStreamWriter

OutputStreamWriter

 
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset like UTF-8.
 
So, we can create a FileOutputStream and then wrap it in an OutputStreamWriter, which allows us to pass an encoding in the constructor.
 

Example

 

package com.topjavatutorial.app;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class UTF8WriterDemo {

  public static void main(String[] args) {
    Writer out = null;
    try {
      out = new BufferedWriter(
          new OutputStreamWriter(new FileOutputStream("c://blogs//temp.txt"), "UTF-8"));

      String text = "This text will be added to File !!";

      out.write(text);
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}


 

Output

 
temp.txt at c:/blogs folder contains following text :
 

write file in java

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags