The i18n Cookbook - recipies for a global society

  • java cookbook
  • about the author
Home › Java Internationalization Cookbook › Unicode, Transliteration, and Charactersets

Java Cookbook

  • Java Internationalization Cookbook
    • Locales
    • Dates and Times
    • Numerical Systems
    • Misc
    • Resource Bundles
    • Unicode, Transliteration, and Charactersets
      • Convert text from one script to another
      • Detect the Charset of a URL
      • Get Transliterators available source ids
      • Get all available transliterator ids
      • Get available target ids for a Transliterator source id
      • Read a Unicode file
      • Write a Shift_JIS Japanese file

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.

‹ Read a Unicode file up
  • encoding
  • io
  • Printer-friendly version

If you are testing any of these recipes in Eclipse and the characters are not displaying correctly in your console visit http://i18ncookbook.com/eclipse_settings.

This site is ad supported.  I hope you find something among our sponsors worth clicking. ;)

i18n search

Google
Custom Search

Search

Tags in Tags

calendar date icu4j Java Locale number format numberformat parse spellout timezone transliteration transliterator
more tags

User login

  • Create new account
  • Request new password
  • java cookbook
  • about the author