Monday, 25 April 2011

Java PrintWriter character encoding example

Some peculiarities about Java PrintWriter:
  1. PrintWriter never throws any exceptions. From JavaDoc:

    Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().

    When error occurs, you'll never know anything more than that it occured, because checkError returns boolean.
  2. When a character is out of the range of the character encoding of the PrintWriter, it prints a question mark (?). But this is not an error.


Test code:
import java.io.*;

public class TestPrintWriter {
public static void main(String[] args) throws Exception {
// abçdef
String latin1 = "ab\347def";

// Unicode for Chinese characters for welcome
String chinese = "\u6B22\u8FCE";

PrintWriter pw;
if (args.length > 0) {
pw = new PrintWriter(
new OutputStreamWriter(
System.out,
args[0]
)
);
}
else {
pw = new PrintWriter(System.out);
}

// print out strings with default encoding, or encoding
// specified as argument.
pw.println(latin1);
pw.println(chinese);
System.out.println("Any error? " + pw.checkError());
}
}


Latin1 test result:
java TestPrintWriter iso-8859-1 | od -bc
0000000 141 142 347 143 144 145 146 015 012 077 077 015 012 101 156 171
a b 347 c d e f \r \n ? ? \r \n A n y
0000020 040 145 162 162 157 162 077 040 146 141 154 163 145 015 012
e r r o r ? f a l s e \r \n
0000037


UTF-8 test result:
java TestPrintWriter utf-8 | od -bc
0000000 141 142 303 247 143 144 145 146 015 012 346 254 242 350 277 216
a b 303 247 c d e f \r \n 346 254 242 350 277 216
0000020 015 012 101 156 171 040 145 162 162 157 162 077 040 146 141 154
\r \n A n y e r r o r ? f a l
0000040 163 145 015 012
s e \r \n
0000044


Also, the constructor throws a FileNotFoundException when you try to write to a read-only file:
C:\work>java TestPrintWriter
Exception in thread "main" java.io.FileNotFoundException: C:\tmp\ReadonlyFile.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
at java.io.PrintWriter.<init>(PrintWriter.java:146)
at TestPrintWriter.main(TestPrintWriter.java:25)

No comments:

Post a Comment