日期:2014-05-20  浏览次数:20777 次

PrintWrite 讨论
PrintWriter out = getResponse().getWriter();  
out.print(value);
out.flush();
out.close();
out = null;

这是一段代码,没什么关系,主要是引出问题 
------------------------------果断割-------------------------------------------
看了一下Writer 和 PrintWriter 的source. 但是看的很晕(本人很菜),有几个问题,希望gs能给讲解一下。

先看下Writer类:
Writer 是个abstract类,里面定义了3个抽象方法,如下:
abstract public void write(char cbuf[], int off, int len) throws IOException; //在这个类里大部分定义的打印方法都依赖于这个方法
abstract public void flush() throws IOException;
abstract public void close() throws IOException;
(ps:这3个方法都是抽象方法,那应该是在继承类里实现这3个方法。)

再看下PrintWriter类:
public class PrintWriter extends Writer //从类的定义处一看就知道是继承了Writer
protected Writer out; //定义个类成员Writer

public void write(char buf[], int off, int len) {
try {
synchronized (lock) {
ensureOpen();
out.write(buf, off, len);
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
  }

 public void close() {
try {
synchronized (lock) {
if (out == null)
return;
out.close();
out = null;
}
}
catch (IOException x) {
trouble = true;
}
  }

public void flush() {
try {
synchronized (lock) {
ensureOpen();
out.flush();
}
}
catch (IOException x) {
trouble = true;
}
  }

问题:
1.PrintWriter中的write方法不是调用的自身吗?
2.close方法和flush方法具体是怎么实现的?


ps:肯定是本人理解错了,求解

------解决方案--------------------
应该就是自身吧,子类会覆盖父类的方法,close和flush直接调用即可,先看具体代码的话,开源的嘛,可以找下,myeclipse就可以
------解决方案--------------------
问题讨论区


------解决方案--------------------
PrintWrite其实不是一个真正的实现类
它和IO里其他的一些包装类类似,采用了一种包裹式的设计模式

pw里不是包裹了一个Writer吗,这个Writer的实现才是真正的IO输出实现,(当然也有可能再进一层或几层,这个要看实际处理时,注入的writer实现了)

pw的三个方法,只是把动作转交给了writer而已