字节流读取文件

ε祈祈猫儿з 提交于 2019-12-02 11:22:44

InputStream:
字节输入流的超类.
1.read():读取一个字节并返回,没有字节返回-1
2.read(byte[] b):读取一定量的字节数,并存储到字节数组中,返回读取到的字节数
用于读取文件的字节输入流对象,FileInputStream()

public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("tempfile/file.txt");

        //创建一个字节流输入对象
        FileInputStream fis = new FileInputStream(file);

        //读取数据
        /*
        第一种读取文件方法
         */
        //1.1
//        int read1 = fis.read();//读取下一个字节
//        System.out.println("ch1="+read1);
//        int read2 = fis.read();//读取下一个字节
//        System.out.println("ch1="+read2);

        //1.2
//        int ch = 0;
//        while((ch = fis.read()) != -1){   //循环n次
//            System.out.println("ch="+(char)ch);
//        }
        //最后会有文件结束标识

        /*
        第二种读取方法
         */
        byte[] buf = new byte[4096];//长度可以定义为1024的整数倍
        //2.1
        int len = 0;
        while((len = fis.read(buf))!= -1){     //循环n/1024次
            System.out.println(new String(buf,0,len));
        }

        //2.2
//        int len1 = fis.read(buf);//从此输入流中将 byte.length 个字节的数据读入一个 byte 数组中。返回读取到的数量
//        System.out.println(len1+":"+new String(buf,0,len1));//String的构造方法,用这种方法保证安全性
//        int len2 = fis.read(buf);//从此输入流中将 byte.length 个字节的数据读入一个 byte 数组中。返回读取到的数量
//        System.out.println(len2+":"+new String(buf,0,len2));

        fis.close();
    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!