Convert with Java methods
The Java™ methods getBytes(), getString(), InputStreamReader(), and OutputStreamWriter() take a code-set parameter that converts to and from Unicode and the specified code set.
Here is sample code that shows how to convert a file from
the client code set to Unicode and then from Unicode to the database
code set:
File infile = new File("data_jpn.dat"); File outfile = new File ("data_conv.dat");.. .pstmt = conn.prepareStatement("insert into t_text values (?)");.. .// Convert data from client encoding to database encoding System.out.println("Converting data ...\n"); try { String from = "SJIS"; String to = "8859_1"; convert(infile, outfile, from, to); } catch (Exception e) { System.out.println("Failed to convert file"); } System.out.println("Inserting data ...\n"); try { int fileLength = (int) outfile.length(); fin = new FileInputStream(outfile); pstmt.setAsciiStream(1 , fin, fileLength); pstmt.executeUpdate(); } catch (Exception e) { System.out.println("Failed to setAsciiStream"); }.. .public static void convert(File infile, File outfile, String from, String to) throws IOException { InputStream in = new FileInputStream(infile); OutputStream out = new FileOutputStream(outfile); Reader r = new BufferedReader( new InputStreamReader( in, from)); Writer w = new BufferedWriter( new OutputStreamWriter( out, to)); //Copy characters from input to output. The InputStreamReader converts // from the input encoding to Unicode, and the OutputStreamWriter // converts from Unicode to the output encoding. Characters that can // not be represented in the output encoding are output as '?' char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.flush(); w.close(); }
When you retrieve data from the database, you can use the same approach to convert the data from the database code set to the client code set.