Write file in UTF-8 encoding using java.nio.file.Files.newBufferedWriter

In this example, let us see that how to write File in UTF-8 encoding format using BufferedWriter & newBufferedWriter method of java.nio.file.Files. UTF-8 is the character encoding that encodes all unicode characters. The below program is having  two methods  FileWriteUTF8Method1 & FileWriteUTF8Method2  to create files encoded in UTF-8 using BufferedWriter & newBufferedWriter respectively. newBufferedWriter(Path, Charset, OpenOption…)  a static method of java.nio.file.Files creates a new file (if the file does not exist ) or  opens the existing  file to write text to the file and returns BufferedWriter.  For writing the content in UTF Encoding, we have to pass the encoding format utf-8 as argument in BufferedWriter or newBufferedWriter. The below program accepts unicode characters as input through showInputDialog and writes the contents to utftest1.txt & utftest2.txt. Type 0 to finish the input. Use language bar to select language.

The files utftest1.txt & utftest2.txt are created under the folder c:\temp.

package com.javaonline;

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

import javax.swing.JOptionPane;
	public class JavaFileWriteUTF8 {
	 public static void main(String[] args){

		 FileWriteUTF8Method1();
		 FileWriteUTF8Method2();

	 		} 

//using BufferedWritter
	 private static void FileWriteUTF8Method1()
	 {

		 try {
		     File dir = new File("c:\\temp\\utftest1.txt");
		     Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dir), "UTF8"));
		     boolean flag=true;
		     while (flag)
		        {
		    	 String  input = JOptionPane.showInputDialog("Enter any string:  0 to end");

				  if (input.compareTo("0") !=0)
				  {
						  out.append(input);
						  out.write(System.getProperty("line.separator"));
				  } else  flag=false;

		        }
			     out.flush();
			     out.close();
		      }
		     catch (UnsupportedEncodingException e)
		       		{
		    	 	System.out.println(e.getMessage());
		       		}
		     catch (IOException e)
		             {
		        		System.out.println(e.getMessage());
		             }

	 }

//using newBufferedWriter method of java.nio.file.Files
  	private static void FileWriteUTF8Method2()
	 		{
	 		Path path = FileSystems.getDefault().getPath("c:/temp","utftest2.txt");

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

			try  {
					BufferedWriter writer = Files.newBufferedWriter(path, charset);
					String	 input = JOptionPane.showInputDialog("Enter any string in Unicode");
					writer.write(input);
					writer.flush();
					writer.close();
			} catch (IOException x) {
			    System.err.format("IOException: %s%n", x);
			}

	 		}

	}

utftest1.text

utf1

utftest2.txt
utf2

 

Reference : nio.file.Files

You may also like

Leave a Reply

Be the First to Comment!