How can I store and retrieve Unicode or Double Byte data in a file using the java.io libraries?

Joe Sam Shirah

Java supports a number of encodings for use with InputStreamReaders and OutputStreamWriters. By using these classes, it's easy to read and write Unicode or any other supported encodings. Here's some code that writes a Unicode string to a file and then reads it back in. Please note that the sample's emphasis is on Unicode functionality -- obviously more care should be taken with exceptions and file closings in a production program:

import java.io.*;

public class WRUni
   public static void main(String[] args)
     FileOutputStream fos = null;
     OutputStreamWriter osw = null;
     BufferedWriter bw = null;

     FileInputStream fis = null;
     InputStreamReader isr = null;
     BufferedReader br = null;

     String sUni = null;

     { // write a UniCode string to a file
       fos = new FileOutputStream( "javauni.txt" );
       osw = new OutputStreamWriter( fos, "Unicode" );
       bw = new BufferedWriter( osw );

       bw.write( "A1B2C3D4E5" );

       // read a Unicode string from a file
       fis = new FileInputStream( "javauni.txt" );
       isr = new InputStreamReader( fis, "Unicode" );
       br = new BufferedReader( isr );

       while( true )
           sUni = br.readLine();
           if( sUni == null ) { break; } 
           System.out.println( "br value: " + sUni );
         catch( Exception ae )
           System.out.println("ae: " + ae );
       } // end while
     catch( Exception e )
       System.out.println("e: " + e );

   } // end main
}  // End class WRUni

For information on supported encodings by JDK version, check the following URLs -- note that the international version of the JDK is required to use all of the listed encodings.

JDK 1.1

JDK 1.2

JDK 1.3

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.