IO/InputStream

来源:互联网 发布:淘宝店铺模板有什么用 编辑:程序博客网 时间:2024/06/07 07:18

1./**
* 根据read方法返回值的特性,如果独到文件的末尾返回-1,如果不为-1就继续向下读。
* */
private static void showContent(String path) throws IOException {
// 打开流
FileInputStream fis = new FileInputStream(path);
int len = fis.read();
while (len != -1) {
System.out.print((char)len);
len = fis.read();
}
// 使用完关闭流
fis.close();
}
2./**
* 使用字节数组存储读到的数据
* */
private static void showContent2(String path) throws IOException {
// 打开流
FileInputStream fis = new FileInputStream(path);

    // 通过流读取内容    byte[] byt = new byte[1024];//缓冲区太小,数据读取不完    int len = fis.read(byt);    for (int i = 0; i < byt.length; i++) {        System.out.print((char) byt[i]);    }    // 使用完关闭流    fis.close();}3./** * 把数组的一部分当做流的容器来使用 * read(byte[] b,int off,int len) */private static void showContent3(String path) throws IOException {    // 打开流    FileInputStream fis = new FileInputStream(path);    // 通过流读取内容    byte[] byt = new byte[1024];    // 从什么地方开始存读到的数据    int start = 5;    // 希望最多读多少个(如果是流的末尾,流中没有足够数据)    int maxLen = 6;    // 实际存放了多少个    int len = fis.read(byt, start, maxLen);    for (int i = start; i < start + maxLen; i++) {        System.out.print((char) byt[i]);    }    // 使用完关闭流    fis.close();}

4./**
* 使用字节数组当缓冲
* */
private static void showContent5(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
byte[] byt = new byte[1024];
int len = fis.read(byt);
System.out.println(len);
String buffer = new String(byt, 0, len);
System.out.print(buffer,0,len);
}

原创粉丝点击