23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Example 15.7. SourceReader<br />

package com.macfaq.io;<br />

import java.io.*;<br />

public class SourceReader extends FilterReader {<br />

public SourceReader(InputStream in) {<br />

this(new InputStreamReader(in));<br />

}<br />

public SourceReader(Reader in) {<br />

super(new BufferedReader(in));<br />

}<br />

private int backslashParity = 1;<br />

public int read() throws <strong>IO</strong>Exception {<br />

int c = in.read();<br />

if (c != '\\') return c;<br />

backslashParity *= -1;<br />

// If there are an even number of backslashes,<br />

// this is not a Unicode escape.<br />

if (backslashParity == 1) return c;<br />

// Mark is supported because I used<br />

// a BufferedReader in the constructor.<br />

in.mark(1);<br />

int next = in.read();<br />

if (next != 'u' ) { // This is not a Unicode escape<br />

in.reset();<br />

return c;<br />

}<br />

// Read next 4 hex digits.<br />

// If the next four chars do not make a valid hex digit<br />

// this is not a valid .java file and you need a compiler error.<br />

StringBuffer sb = new StringBuffer();<br />

sb.append((char) in.read());<br />

sb.append((char) in.read());<br />

sb.append((char) in.read());<br />

sb.append((char) in.read());<br />

String hex = sb.toString();<br />

try {<br />

return Integer.valueOf(hex, 16).intValue();<br />

}<br />

catch (NumberFormatException e) {<br />

throw new <strong>IO</strong>Exception("Bad Unicode escape");<br />

}<br />

}<br />

<strong>Java</strong> I/O<br />

383

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!