itten;
// rethrow exception
throw ex;
}
}
}
彻底转变流,第2部分:优化Java内部I/O(11)
时间:2011-06-21 Merlin Hughes
如清单 16 所示,这个管道流实现的特点之一是写程序可设置一个被传递给 读程序的异常。
清单 16. 设置异常
private synchronized void setException (IOException ex)
throws IOException {
// fail if an exception is already pending
if (exception != null)
throw new IOException ("Exception already set: " + exception);
// throw an exception if the pipe is broken
brokenCheck (WRITER);
// take a reference to the pending exception
this.exception = ex;
// wake any sleeping thread
if (sleeping) {
notify ();
sleeping = false;
}
}
清单 17 给出这个管道的有关输出流的代码。 getOutputStream() 方法返回 OutputStreamImpl ,OutputStreamImpl 是使用前面给出的方法来把数据写到内 部管道的输出流。OutputStreamImpl 类继承了 OutputStreamEx , OutputStreamEx 是允许为读线程设置异常的输出流类的扩展。
清单 17. 输出流
public OutputStreamEx getOutputStream () {
// return an OutputStreamImpl associated with this pipe
return new OutputStreamImpl ();
}
private class OutputStreamImpl extends OutputStreamEx {
private byte[] one = new byte[1];
public void write (int datum) throws IOException {
// write one byte using internal array
one[0] = (byte) datum;
write (one, 0, 1);
}
public void write (byte[] data, int offset, int length)
throws IOException {
// check parameters
if (data == null) {
throw new NullPointerException ();
} else if ((offset < 0) || (offset + length > data.length)
|| (length < 0)) {
throw new IndexOutOfBoundsException ();
} else if (length > 0) {
// call through to writeImpl()
PipeInputStream.this.writeImpl (data, offset, length);
}
}
public void close () throws IOException {
// close the write end of this pipe
PipeInputStream.this.close (WRITER);
}
public void setException (IOException ex) throws IOException {
// set a pending exception
PipeInputStream.this.setException (ex);
}
}
// static OutputStream extension with setException() method
public static abstract class OutputStreamEx extends OutputStream {
public abstract void setException (IOException ex) throws IOException;
}
}
彻底转变流,第2部分:优化Java内部I/O(12)
时间:2011-06-21 Merlin Hughes
使用新的管道流
清单 18 演示了怎样使用新的管道流来解决上一篇文章中的问题。请注意, 写程序线程中出现的任何异常均可在流中被传递。
清单 18. 使用新的管道流
public static InputStream newPipedCompress (final InputStream in)
throws IOException {
PipeInputStream source = new PipeInputStream ();
final PipeInputStream.OutputStreamEx sink = source.getOutputStream ();
new Thread () {
public void run () {
try {
GZIPOutputStream
|