野花一片 2017-03-16 07:20 采纳率: 33.3%
浏览 844

java IO 获取输入流的问题

如下代码:
我在后台输入 1234567890

但是下面这段程序输入是:
1234567890

34567890

多了一段  34567890
 import java.io.*;  
public class Person {  
    public static void main(String args[]) {
        int b =10;
        byte[] x = new byte[b];
        try {
            System.out.println("please Input:");
            while ((b = System.in.read(x, 0, b)) != -1 && (b>0)) {
                String s = new String(x);
                System.out.println(s);
            }
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }  
} 
  • 写回答

1条回答 默认 最新

  • 别让我起名字啊 2017-03-16 08:31
    关注

    以下是我的理解:

        public static void main(String[] args){
            int b =10;
            byte[] x = new byte[b];
            try {
                System.out.println("please Input:");
    /*            while ((b = System.in.read(x, 0, b)) != -1 && (b>0)) {
                    String s = new String(x);
                    System.out.println(s);
                }*/
    
                //下面一行运行完后 s=1234567890 b=10 x=[49, 50, 51, 52, 53, 54, 55, 56, 57, 48] 对应0-9的字节值
                b = System.in.read(x, 0, b);
                String s = new String(x);
                System.out.println(s);
    
                //下面一行运行完后x=[13, 10, 51, 52, 53, 54, 55, 56, 57, 48]因为刚才输入完0-9后又输入了回车符,对应输入了回车符和换行符,字节值为13和10
                b = System.in.read(x, 0, b);
                String s1 = new String(x);
                System.out.println(s1);
    
                //因为没有输入了,所以下面不会被运行
                b = System.in.read(x, 0, b);
                String s2 = new String(x);
                System.out.println(s2);
    
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }
    

    关于System.in.read方法的说明可参考http://blog.csdn.net/foart/article/details/8211327

    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题