zoukankan      html  css  js  c++  java
  • readLine() 和 " "," " 问题

    很多输入流中都有一个函数readLine(),我们也经常使用这个函数,但有时如果不认真考虑,这个函数也会带来一些小麻烦。

    如果我们是从控制台读入的话,我们也许没有想过readLine函数到底是根据" "," "中的哪一个来截取字符串,因为一般计算机的实现时enter键按下后对应的既有" "," ";

    补充说明一下:" "是把光标移到一行的开头," "是换到下一行,不同系统处理方式不一样,Unix系统中" "会移到下一行的开头,Windows则是表面意思。Mac的" "则是回到开头,并移到下一行。

    根据我的测试,readLine返回的字符串中不包含结尾的" "," "。

    例子:

    String line = "hello
    ";
            
            OutputStream out = new FileOutputStream(".//out.txt");
            
            out.write(line.getBytes());
            
            InputStream in = new FileInputStream(".//out.txt");
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    
            String str = reader.readLine();
            
            System.out.println("readLine 读出后的长度: "+str.length()+"     readLine读的结果: "+str);

    输出的结果为:

    readLine 读出后的长度: 5     readLine读的结果: hello

    可以看出,readLine函数会自动截取" "," "之前的字符串。

    String line = "hello
    ";
            
            OutputStream out = new FileOutputStream(".//out.txt");
            
            out.write(line.getBytes());
            
            InputStream in = new FileInputStream(".//out.txt");
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    
            //String str = reader.readLine();
            
            /*System.out.println("readLine 读出后的长度: "+str.length()+"     readLine读的结果: "+str);*/
            
            byte[] b = new byte[100];
            
            in.read(b,0,line.length());
            
            for(int i = 0; i<line.length(); i++){
                System.out.println((char)b[i]);
            }
            System.out.println("end!");

    输出结果:

    h
    e
    l
    l
    o


    end!

    这里看出来如果用read来读的话,则没有这种情况,它会按字节读取。

  • 相关阅读:
    十六、异步编程——messagedialog
    关于委托的一个摘录
    com interop 简述
    [STAThread]的使用
    Python初识和基础语法
    Python基础数据类型以及格式化输出
    JS读取PHP中设置的中文cookie时出现乱码的解决方法
    解决跨域读写Cookies的问题,(ASP、PHP、ASP.NET、JSP)解决方案
    多字段distinct查询
    Dedecms当前位置{dede:field name='position'/}修改,去掉>方法
  • 原文地址:https://www.cnblogs.com/chaiwentao/p/4771231.html
Copyright © 2011-2022 走看看