javaI/O流之节点流(即文件流)

IO流

input\output缩写。对于数据的输入输出以流的方式进行。

输入与输出

将数据读入内存中,是输入
将内存程序中的数据写入到文件中,是输出

流的分类

按数据单位:字节流8bit和字符流16bit
按数据流的流向:输入流和输出流
按流的角色不同:节点流和处理流

抽象基类:

在这里插入图片描述

节点流

FileReader:从文件中把内容读入到内存中,显示到控制台上
FileWrite:从内存中将程序内容写入到文件中,构造器中指明false(FileWriter(file,false)写入文件的内容追加继续写。
结合二者,可实现文件的复制拷贝,代码如下:

@Test
    public void test5(){
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            // 创建File类对象,指明读入和写入的文件
            File file1 = new File("E:\\李威彤\\ihateyou\\hate.txt");
            File file2 = new File("E:\\李威彤\\ihateyou\\hate3.txt");

            // 创建输入流和输出流的对象
            fileReader = new FileReader(file1);
            fileWriter = new FileWriter(file2);

            // 数据的读入和写出操作
            char[] cbuf = new char[5];
            int len; // 记录读入到cbuf数组中的字符的个数
            while ((len = fileReader.read(cbuf)) != -1) {
                fileWriter.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (fileWriter!=null)
                    fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileReader!=null)
                    fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

用字节流实现文件视频的复制

代码如下:

{
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            File src = new File(srcPath);
            File dest = new File(destPath);

            fileInputStream = new FileInputStream(src);
            fileOutputStream = new FileOutputStream(destPath);
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream!=null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileOutputStream!=null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值