7. java.io.InputStream

来源:互联网 发布:万网域名注册网站 编辑:程序博客网 时间:2024/05/19 04:29
/*abstract int    read()Reads the next byte of data from the input stream.int     read(byte[] b)Reads some number of bytes from the input stream and stores them into the buffer array b.int     read(byte[] b, int off, int len)Reads up to len bytes of data from the input stream into an array of bytes. */import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;public class LianXi {    public static void main(String[] args) throws Exception {        InputStream inputStream = null;        try {            inputStream = new FileInputStream("D:/temp/input.txt");//            r(inputStream);            rb(inputStream);        } catch (FileNotFoundException e) {     // 在有多个catch时,只会执行一个范围小的,而不是每一个catch都会执行            System.out.println("文件不存在" + e);        }  finally {            if (inputStream != null) {                inputStream.close();            }        }    }    public static void r(InputStream inputStream) throws Exception {        int data;        while((data = inputStream.read()) != -1) {            System.out.print((char)data);       // This is input file.        }        System.out.println();    }    public static void rb(InputStream inputStream) throws Exception{        System.out.println("---------------------------");        byte[] bytes = new byte[25];        while((inputStream.read(bytes, 1, 11)) != -1) {            System.out.print(bytes);       // [B@65b54208[B@65b54208        }        System.out.println();        for (byte b : bytes) {            if (b == 0) {                System.out.print("-");      // 15个- 10个byte,共有25个字节            }            System.out.print((char)b);        }        System.out.println();        /*            一次性读取一个字节数组的方式,比一次性读取一个字节的方式快的多,所以,尽可能使用read(byte[] b, int off, int len)和read(byte[] b)方法。         */    }}
原创粉丝点击