Java Reference
In-Depth Information
Example 7-2 shows a simple program that works with character encodings. It con-
verts a file from one specified encoding to another by converting from the first
encoding to Unicode and then from Unicode to the second encoding. Note that
most of the program is taken up with the mechanics of parsing argument lists,
handling exceptions, and so on. Only a few lines are required to create the Input-
StreamReader and OutputStreamWriter classes that perform the two halves of the
conversion. Also note that exceptions are handled by calling LocalizedError.dis-
play() . This method is not part of the Java API; it is a custom method shown in
Example 7-5 at the end of this chapter.
Example 7−2: ConvertEncoding.java
package com.davidflanagan.examples.i18n;
import java.io.*;
/** A program to convert from one character encoding to another */
public class ConvertEncoding {
public static void main(String[] args) {
String from = null, to = null;
String infile = null, outfile = null;
for(int i = 0; i < args.length; i++) { // Parse command-line arguments.
if (i == args.length-1) usage(); // All args require another.
if (args[i].equals("-from")) from = args[++i];
else if (args[i].equals("-to")) to = args[++i];
else if (args[i].equals("-in")) infile = args[++i];
else if (args[i].equals("-out")) outfile = args[++i];
else usage();
}
try { convert(infile, outfile, from, to); } // Attempt conversion.
catch (Exception e) { // Handle exceptions.
LocalizedError.display(e); // Defined at the end of this chapter.
System.exit(1);
}
}
public static void usage() {
System.err.println("Usage: java ConvertEncoding <options>\n" +
"Options:\n\t-from <encoding>\n\t" +
"-to <encoding>\n\t" +
"-in <file>\n\t-out <file>");
System.exit(1);
}
public static void convert(String infile, String outfile,
String from, String to)
throws IOException, UnsupportedEncodingException
{
// Set up byte streams.
InputStream in;
if (infile != null) in = new FileInputStream(infile);
else in = System.in;
OutputStream out;
if (outfile != null) out = new FileOutputStream(outfile);
else out = System.out;
// Use default encoding if no encoding is specified.
if (from == null) from = System.getProperty("file.encoding");
if (to == null) to = System.getProperty("file.encoding");
Search WWH ::




Custom Search