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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

question is what to do if the input text contains an unescaped backslash. The easiest and most<br />

robust solution is to replace it with \u005C, the Unicode escape for the backslash itself.<br />

Example 15.8. SourceWriter<br />

package com.macfaq.io;<br />

import java.io.*;<br />

public class SourceWriter extends FilterWriter {<br />

{<br />

}<br />

public SourceWriter(Writer out) {<br />

super(out);<br />

}<br />

public void write(char[] text, int offset, int length) throws <strong>IO</strong>Exception<br />

}<br />

for (int i = offset; i < offset+length; i++) {<br />

this.write(text[i]);<br />

}<br />

public void write(String s, int offset, int length) throws <strong>IO</strong>Exception {<br />

}<br />

for (int i = offset; i < offset+length; i++) {<br />

this.write(s.charAt(i));<br />

}<br />

public void write(int c) throws <strong>IO</strong>Exception {<br />

}<br />

// We have to escape the backslashes below.<br />

if (c == '\\') out.write("\\u005C");<br />

else if (c < 128) out.write(c);<br />

else {<br />

String s = Integer.toHexString(c);<br />

// Pad with leading zeroes if necessary.<br />

if (c < 256) s = "00" + s;<br />

else if (c < 4096) s = "0" + s;<br />

out.write("\\u");<br />

out.write(s);<br />

}<br />

15.11.3 PushbackReader<br />

The PushbackReader class is a filter that provides a pushback buffer around a given reader.<br />

This allows a program to "unread" the last character it read. It's similar to<br />

PushbackInputStream , discussed in Chapter 6, but instead of pushing back bytes, it pushes<br />

back chars. Both PushbackReader and BufferedReader use buffers, but only<br />

PushbackReader allows unreading and only BufferedReader allows marking and resetting.<br />

The difference is that pushing back characters allows you to unread characters after the fact.<br />

Marking and resetting requires you to mark in advance the location you want to reset to.<br />

385

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

Saved successfully!

Ooh no, something went wrong!