JAVA-IO-字节流-字符流-缓冲流-File,看这个


一、IO流分类

1.字节流处理任何数据文件;
2.字符流只能处理纯文本文件;
3.缓冲流基本原理,在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。
字节缓冲流:BufferedInputStream,BufferedOutputStream;
字符缓冲流: BufferedReader,BufferedWriter;

在这里插入图片描述

二、字节流、文件、缓冲流 的使用

流程思路 :file对象 -> file输入流 --> 字节缓冲输入流 --> 字节数组输入流 --> 数组 --> 字节缓冲输出流 --> file输出流 -->文件

代码如下(示例):

import java.io.*;

public class Aopmain {
    public static void main(String[] args) throws IOException {

        File file = new File("E:\\PaybillFile\\pdf\\aaa.pdf");
        System.out.println(file.getName());         //aaa.pdf
        System.out.println(file.getPath());         //E:\PaybillFile\pdf\aaa.pdf
        System.out.println(file.getAbsoluteFile());//E:\PaybillFile\pdf\aaa.pdf
        System.out.println(file.getAbsolutePath());//E:\PaybillFile\pdf\aaa.pdf
       /*
        boolean createNewFile(); //创建文件
        boolean mkdir();创建文件夹
        boolean mkdirs();创建多级文件夹。*/


        //本地已有的要发送的文件
        File sendFile = new File("D:\\PaybillFile\\sendpdf\\send01.pdf");
        //接收文件夹及文件
        File receiveFile = new File("D:\\PaybillFile\\sendpdf\\receiveFile.pdf");
        //创建文件夹及文件
        receiveFile.createNewFile();

        //将sendFile 放入文件字节流
        FileInputStream  fileIO = new FileInputStream(sendFile);

        //将文件字节流,放到字节缓冲区,通过缓冲区读写,减少系统IO次数
        BufferedInputStream bufferIn01 = new BufferedInputStream(fileIO);

        //建一个字节数组输出流,让缓冲流写入
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();

        byte[] bt = new byte[1024];

        int length = -1;

        //bufferIn -> bt :从bufferIn流中读1024个字节到 bt, 读完则length=-1;
        while((length = bufferIn01.read(bt))!=-1){

            //bt -> byteOut :从bt写到byteOut流中
            byteOut.write(bt,0,length);
        }

        //将字节数组输出流,输出到数组
        byte[] receiveByte = byteOut.toByteArray();

        //文件输出流-->接收文件
        FileOutputStream fileOut = new FileOutputStream(receiveFile);

        //字节缓冲输出流 --> 文件输出流
        BufferedOutputStream bufferOut = new BufferedOutputStream(fileOut);

        //将字节数组 --> 字节缓冲输出流
        bufferOut.write(receiveByte);

        //关流,注意关流顺序
        fileIO.close();
        bufferIn01.close();
        byteOut.flush();
        byteOut.close();
        bufferOut.flush();
        bufferOut.close();
        fileOut.flush();;
        fileOut.close();
    }
}

2.字符流、文件、缓冲流的使用(同字节流思路一样)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值