Write a Shift_JIS Japanese file

Problem:

You want to write a file to disk in an encoding other than the default.

Solution:

The convenience FileWriter class writes files in the default character encoding of the JVM.  If you want to specify an encoding you should create a FileOutputStream and pass it to an OutputStreamWriter.  The OutputStreamWriter class allows you to specify an encoding Charset.

To write a file to disk as Shift_JIS:

//Handle potential exceptions
try{
   //Our text to write out to the file. In this case garbage Japanese
   String example = "これはテストです。高松日本米国英国世界";
   //Create an output stream
   FileOutputStream fos = new FileOutputStream("C:\\files \\testOut.html");
   //Create a writer specifying our output stream and character set.
   OutputStreamWriter osw = new OutputStreamWriter(fos,"Shift_JIS");
   //Let's buffer it for performance
   BufferedWriter bw = new BufferedWriter(osw);
   //write the file bw.write(example);
   //close the writer bw.close();
} catch (FileNotFoundException e){
   e.printStackTrace();
} catch (IOException e){
   e.printStackTrace();
}


to test the output open the file in your browser and change the encoding to Shift_JIS.