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.

public class DecimalFilter extends DumpFilter {<br />

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

protected int numRead = 0;<br />

protected int breakAfter = 15;<br />

protected int ratio = 4; // number of bytes of output per byte of input<br />

public DecimalFilter(InputStream in) {<br />

super(in);<br />

}<br />

protected void fill() throws <strong>IO</strong>Exception {<br />

}<br />

buf = new int[ratio];<br />

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

this.numRead++;<br />

if (datum == -1) {<br />

// Let read() handle end of stream.<br />

throw new EOFException();<br />

}<br />

String dec = Integer.toString(datum);<br />

if (datum < 10) { // Add two leading zeros.<br />

dec = "00" + dec;<br />

}<br />

else if (datum < 100) { // Add leading zero.<br />

dec = '0' + dec;<br />

}<br />

for (int i = 0; i < dec.length(); i++) {<br />

buf[i] = dec.charAt(i);<br />

}<br />

if (numRead < breakAfter) {<br />

buf[buf.length - 1] = ' ';<br />

}<br />

else {<br />

buf[buf.length - 1] = '\n';<br />

numRead = 0;<br />

}<br />

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

return (buf.length - index) + ratio * in.available();<br />

}<br />

// With some extra effort, you could provide more efficient<br />

// implementations of these methods. You could even support<br />

// marking and resetting.<br />

/*<br />

public int read(byte[] data, int offset, int length) throws <strong>IO</strong>Exception<br />

{}<br />

public long skip(long bytesToSkip) throws <strong>IO</strong>Exception {}<br />

public synchronized void mark(int readlimit) {}<br />

public synchronized void reset() throws <strong>IO</strong>Exception {}<br />

public boolean markSupported() {}<br />

*/<br />

}<br />

Example 6.11. HexFilter<br />

package com.macfaq.io;<br />

import java.io.*;<br />

92

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

Saved successfully!

Ooh no, something went wrong!