Java io流System.in.read()如何使用

开门见山 解决问题

这里提到的read()方法是指java.io包下InputStream里的read()。InputStream类提供了一个抽象read方法及它的两个重载方法,分别是:

abstract int read() //从键盘缓冲区读取一个字节,返回该字节的ASCII码

int read(byte[] b) //从键盘缓冲区读取一个字节数组,返回字节数

int read(byte[] b,int off,int len) //  从键盘缓冲区读取宇哥字节数组,off为偏移量,len为可读入的最大字节数,返回实际读入的字节数


  • 先看第一个read():

    	public test () throws IOException {
    		
    		len=System.in.read();
    		System.out.print(len+" ");
    		
    		len=System.in.read();
    		System.out.print(len+" ");
    		
    		len=System.in.read();
    		System.out.println(len);
    			
    	}

    控制台输入:123  结果显示1,2,3对应的ASCII码值:

       

       但当控制台只输入回车,结果是:

        

        原因是回车也会被读取,也就是回车代表的“\r”和“\n”也会被读取,而“\r”和“\n”对应的ASCII码值为13和10。

        另外,用强转可以直接得到输入的数据:

	public test () throws IOException {
		
		char a = (char)System.in.read();
		System.out.println(a);

	}

 

  • 再来第二个read():

     

    	public test () throws IOException {
    		
    		byte[]  b = new byte[256];
    		InputStream in = System.in; 
    		int a = in.read(b); //也可以这样调用
    		System.out.println(a);
    
    	}

    控制台输入:123  结果显示1,2,3 加上“\r”和“\n”后的字节数:

       

  • 第三个read():

     其实查看int read(byte[] b)的源码可以看到,该方法会调用第三个read方法

public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }

      接着看int read(byte b[], int off, int len)的源码,而该方法内又会调用无参的read方法:

 public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException(); //空指针异常
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException(); //数组下标越界异常
        } else if (len == 0) {
            return 0;
        }

        int c = read();
        if (c == -1) {
            return -1;
        }
        b[off] = (byte)c;//第一个读入的字节在b中的偏移量

        int i = 1;
        try {
            for (; i < len ; i++) {
                c = read(); //调用无参read方法
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte)c;
            }
        } catch (IOException ee) {
        }
        return i;
    }

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值