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

java编程思想中TestStram求解释
// 这是测试类,用于替换标准控制台输出和控制台错误来拦截控制台输出。

public class TestStream extends PrintStream {
protected int numofLines;
private PrintStream
console = System.out,
err = System.err,
fout;
// To Store lines sent to System.out or err
private InputStream stdin;
private String className;
public TestStream(String className){
// Autoflush
super(System.out, true); 
System.setOut(this);
System.setErr(this);
// Save to restore in dispose()
stdin = System.in;
// Replace the default version with one that
// automatically produces input on demand:
System.setIn(new BufferedInputStream(new InputStream(){ //这段代码不是很理解,求解
char[] input = ("test\n").toCharArray();
int index = 0;
public int read(){
return
(int)input[index = (index + 1) % input.length];
}
})); this.className = className;
openOutputFile();
}
// This will write over an old Output.txt file;
public void openOutputFile() {
try{
fout = new PrintStream(new FileOutputStream(
new File(className + "Output.txt")));
}catch(FileNotFoundException e){
throw new RuntimeException(e);

}
}

------解决方案--------------------
我觉着看下api就知道了
System.setIn

setIn
public static void setIn(InputStream in)重新分配“标准”输入流。 
首先,如果有安全管理器,则通过 RuntimePermission("setIO") 权限调用其 checkPermission 方法,查看是否可以重新分配“标准”输入流。 



参数:
in - 新的标准输出流。 
抛出: 
SecurityException - 如果安全管理器存在并且其 checkPermission 方法不允许重新分配标准输入流。
从以下版本开始: 
JDK1.1 
另请参见:
SecurityManager.checkPermission(java.security.Permission), RuntimePermission



BufferedInputStream
public BufferedInputStream(InputStream in)创建一个 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。创建一个内部缓冲区数组并将其存储在 buf 中。 

参数:
in - 底层输入流。



public abstract class InputStreamextends Objectimplements Closeable此抽象类是表示字节输入流的所有类的超类。 

需要定义 InputStream 子类的应用程序必须总是提供返回下一个输入字节的方法。 



------解决方案--------------------
匿名内部类,这个InputStream是由匿名内部类实现的,这个类类似于InputStream的子类,只是重写了public int read()方法