IO流——字节流

一.IO流
    Input 输入流:从文件读取内容,文件对于我来说是输入流
    Output 输出流:向文件写入内容,文件对我来说是输出流
二.字节流
    1.以字节为单位来操控数据
    2.文件输入流:FileInputStream是InputStream这个抽象类的子类
        读取内容:一次读取一个字节
        读取的步骤:a.创建输入流对象 FileInputStream fis = new FileInputStream("1.txt")
                  b.调用read()方法读取内容int read = fis.read();一次只能读一个字节 为了方便读取,可以用循环来进行改写,一次可以读取多个字节
            FileInputStream fis = new FileInputStream("1.txt")
            byte[] buf = new byte[2];
         while(true) {
            int read = fis.read(buf);
            if(read == -1) {
                break;
            }
            System.out.println(read);
            fis.close();
        特点:流是单向的
    3.文件输出流:FileOutputStream是OutputStream这个抽象类的子类
            步骤:
            a.创建输出流对象FileOutputStream fos = new FileOutputStream("2.txt");
            b.向输出流写入内容
                    fos.write(97);
                    fos.write(98);
                    fos.write(99);
             c.关闭输出流
                     fos.close();
三.文件的复制
        FileInputStream fis = new FileInputStream("1.txt");
        FileOutputStream fos = new FileOutputStream("3.txt");

        while(true) {
            byte[] buf = new byte[1024];
            int len = fis.read(buf);
            if(len == -1) {
                break;
            }
            fos.write(buf, 0, len); 
        }

        fis.close();
        fos.close();                                            

猜你喜欢

转载自blog.csdn.net/woshijinfeixi/article/details/81607456