InputStream中3个read方法的区别

 

3个read方法的区别

read()读取1个字节
read(byte[] b)将文本中的所有数据读取到b这个字节数组中
read(byte[] b, int off, int len)从流的第off个字节开始,读入长度为len的字节的数据

 

*****************read()*****************

package com.xuzhiwen.io1;

import java.io.File;
import java.io.FileInputStream;

public class InputStreamTest {
    public static void main(String[] args) throws Exception {
        String s = File.separator;
        File file = new File("E:"+s+"filetest"+s+"11.txt");
        FileInputStream in = new FileInputStream(file);
        int i;
        while((i=in.read()) != -1){
            System.out.println((char)i);
        }
    }
}

11.TXT文件内容:

运行程序输出结果为:

 

*****************read(byte[] b)*****************

返回值为:实际读取的字节数

package com.xuzhiwen.io1;

import java.io.File;
import java.io.FileInputStream;

public class InputStreamTest {
    public static void main(String[] args) throws Exception {
        String s = File.separator;
        File file = new File("E:"+s+"filetest"+s+"11.txt");
        FileInputStream in = new FileInputStream(file);
        int len;
        byte b[] = new byte[1024];
        while((len = in.read(b)) != -1){
            System.out.println(new String(b));
        }
    }
}

运行结果如下:

 

*****************?*****************

 

posted @ 2017-08-14 14:44  beibidewomen  阅读(2956)  评论(0编辑  收藏  举报