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

Java中IO流问题--System.in
System.in 是返回一个InputSteam,这个InputStream中有个read()方法,可以读字节。
但我查了API和源码,read()是一个抽象方法啊,为什么还是能用呢?是什么去实现了?
那段源码也是完全没看懂,怎么是返回一个nullInputStream()的返回值是Null啊。


 /**
     * The "standard" input stream. This stream is already
     * open and ready to supply input data. Typically this stream
     * corresponds to keyboard input or another input source specified by
     * the host environment or user.
     */
    public final static InputStream in = nullInputStream();

/**
     * The following two methods exist because in, out, and err must be
     * initialized to null.  The compiler, however, cannot be permitted to
     * inline access to them, since they are later set to more sensible values
     * by initializeSystemClass().
     */
    private static InputStream nullInputStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
    return null;
}
throw new NullPointerException();
    }


哪个大神来给解释下?解释懂了,以身相许啊。。。

PS:还有个小问题
是不是System.in会自动捕捉\r\n回车换行符?当有这个符号时,就认为用户输入完毕?

大神快点来!!!可惜木有@功能。

源码 java io流

------解决方案--------------------
如果一个类,以一抽象类作为参数,应该需要实现这个抽象类中的方法。
所以System类中的in方法中的read()方法,可能在某个看不到的角落里实现了。

public abstract class DemoAClass {
    
    int i;
    public abstract void read();
}

public class DemoClassI {
    DemoAClass a;

    public DemoClassI() 
    {
        this.a = new DemoAClass()
        {
            public void read()
            {
                i=100000;
            }
        };
    }
    
}

就像上面这两个类一样。这个read() 在这个类中就有了自己的功能。



是不是System.in会自动捕捉\r\n回车换行符?当有这个符号时,就认为用户输入完毕?

这个应该也属于系统属性吧。在控制台不断的输入字符,敲一下回车,就会将把信息送入到in的read方法中。
。。。。
。。
说下自己的想法,非解答。
------解决方案--------------------
可以举个例子
FilterInputStream继承了InputStream复写了read()方法
  public int read() throws IOException {
        return in.read();
    }

这里in还是InputStram的引用
BufferedInputStream继承了FilterInputStream复写了FilterInputStream的read方法
  public synchronized int read() throws IOException {
        if (pos >= count) {
            fill();
            if (pos >= count)
                return -1;
        }
        return getBufIfOpen()[pos++] & 0xff;
    }