当前位置: 首页 > news >正文

Java 读写文件 字节流 缓冲流 转换流 对象流

Java 读写文件 字节流 缓冲流 转换流 对象流

一、Java 中有哪些流

二、Java 中流的分类

  • 节点流(从文件内容到流的输入输出)
    • 字节流 FileInputStream FileOutputStream
    • 字符流 FileReader FileWriter
  • 处理流(基于节点流的进一步封装)
    • 缓冲流 BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
    • 转换流 DataInputStream DataOutputStream
    • 对象流 ObjectInputStream ObjectOutputStream

三、Java 中流如何使用

  • 字节流
    • 可以读写文本、图片、音频、视频等各种类型的文件。
    • 比如 world、png、mp4 等。
  • 字符流
    • 只可以读写文本文件
    • 比如 txt、java、py、c 等。
    • 注意 world excel ppt 不属于文本文件。
  • 缓冲流
    • 作用:先把数据缓存到内存中,然后批量写入磁盘中,减少跟磁盘交互的次数,可以提高读写文件的效率。
    • 如果不使用缓冲流,读一次写一次跟磁盘交互一次,跟磁盘交互次数多,读写效率较低。
  • 转换流
    • 用于文件内容的编码和解码,文件内容中保存的是二进制数据,解码后,我们才可以看懂。
    • 解码,把二进制数据按照指定的字符集转换为字符。
    • 编码,把字符按照指定字符集编码为二进制数据。
  • 对象流
    • 用于把对象序列化为二进制数据,以便持久化到磁盘或使用网络传输。
    • 反序列化,把二进制数据反序列化为内存中的 Java 对象。

四、使用字节流读写文件


publicvoidcopyFileWithFile(StringsrcPath,StringdestPath){FileInputStreamfis=null;FileOutputStreamfos=null;try{//1.FilesrcFile=newFile(srcPath);FiledestFile=newFile(destPath);//2.fis=newFileInputStream(srcFile);fos=newFileOutputStream(destFile);//3. 读写过程intlen;byte[]buffer=newbyte[100];while((len=fis.read(buffer))!=-1){fos.write(buffer,0,len);}}catch(IOExceptione){e.printStackTrace();}finally{//4. 关闭资源try{if(fos!=null)fos.close();}catch(IOExceptione){e.printStackTrace();}try{if(fis!=null)fis.close();}catch(IOExceptione){e.printStackTrace();}}}

五、使用缓冲流读写文件

publicvoidcopyFileWithBuffered(StringsrcPath,StringdestPath){BufferedInputStreambis=null;BufferedOutputStreambos=null;try{//1.FilesrcFile=newFile(srcPath);FiledestFile=newFile(destPath);//2.FileInputStreamfis=newFileInputStream(srcFile);FileOutputStreamfos=newFileOutputStream(destFile);bis=newBufferedInputStream(fis);bos=newBufferedOutputStream(fos);//3. 读写过程intlen;byte[]buffer=newbyte[100];while((len=bis.read(buffer))!=-1){bos.write(buffer,0,len);}}catch(IOExceptione){e.printStackTrace();}finally{//4. 关闭资源(1. 需要先关闭缓冲流,再关闭文件流 2. 默认情况下,关闭外层流时,也会自动关闭内部的流)try{if(bos!=null)bos.close();}catch(IOExceptione){e.printStackTrace();}try{if(bis!=null)bis.close();}catch(IOExceptione){e.printStackTrace();}//可以省略// fos.close();// fis.close();}}


六、字符流只能读写文本文件

publicvoidtest(){InputStreamReaderisr=null;OutputStreamWriterosw=null;try{isr=newInputStreamReader(newFileInputStream("康师傅的话.txt"),"gbk");osw=newOutputStreamWriter(newFileOutputStream("C:\\Users\\shkstart\\Desktop\\寄语.txt"),"utf-8");char[]cbuf=newchar[1024];intlen;while((len=isr.read(cbuf))!=-1){osw.write(cbuf,0,len);osw.flush();}System.out.println("文件复制完成");}catch(IOExceptione){e.printStackTrace();}finally{try{if(isr!=null)isr.close();}catch(IOExceptione){e.printStackTrace();}try{if(osw!=null)osw.close();}catch(IOExceptione){e.printStackTrace();}}}

七、使用转换流进行解码编码

使用 UTF8 解码文件得到文件内容后使用 GBK 编码文件输出到新的文件中

publicvoidtest4(){InputStreamReaderisr=null;OutputStreamWriterosw=null;try{//1. 造文件Filefile1=newFile("dbcp_gbk.txt");Filefile2=newFile("dbcp_gbk_to_utf8.txt");//2. 造流FileInputStreamfis=newFileInputStream(file1);//参数2对应的是解码集,必须与dbcp_gbk.txt的编码集一致。isr=newInputStreamReader(fis,"GBK");FileOutputStreamfos=newFileOutputStream(file2);//参数2指明内存中的字符存储到文件中的字节过程中使用的编码集。osw=newOutputStreamWriter(fos,"utf8");//3. 读写过程char[]cBuffer=newchar[1024];intlen;while((len=isr.read(cBuffer))!=-1){osw.write(cBuffer,0,len);}System.out.println("操作完成");}catch(IOExceptione){thrownewRuntimeException(e);}finally{//4. 关闭资源try{if(osw!=null)osw.close();}catch(IOExceptione){thrownewRuntimeException(e);}try{if(isr!=null)isr.close();}catch(IOExceptione){thrownewRuntimeException(e);}}}

八、使用对象流序列化反序列化


person 对象

packagecom.atguigu05.objectstream;importjava.io.Serializable;publicclassPersonimplementsSerializable{//Serializable:属于一个标识接口Stringname;intage;intid;Accountacct;staticfinallongserialVersionUID=422334254234L;publicPerson(){}publicPerson(Stringname,intage){this.name=name;this.age=age;}publicPerson(Stringname,intage,intid){this.name=name;this.age=age;this.id=id;}publicPerson(Stringname,intage,intid,Accountacct){this.name=name;this.age=age;this.id=id;this.acct=acct;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}@OverridepublicStringtoString(){return"Person{"+"name='"+name+'\''+", age="+age+", id="+id+", acct="+acct+'}';}}classAccountimplementsSerializable{doublebalance;staticfinallongserialVersionUID=422234L;publicAccount(doublebalance){this.balance=balance;}@OverridepublicStringtoString(){return"Account{"+"balance="+balance+'}';}}

序列化 person 对象

publicvoidtest3(){ObjectOutputStreamoos=null;try{Filefile=newFile("object1.dat");oos=newObjectOutputStream(newFileOutputStream(file));//2.写出数据即为序列化的过程Personp1=newPerson("Tom",12);oos.writeObject(p1);oos.flush();Personp2=newPerson("Jerry",23,1001,newAccount(2000));oos.writeObject(p2);oos.flush();}catch(IOExceptione){thrownewRuntimeException(e);}finally{try{if(oos!=null)oos.close();}catch(IOExceptione){thrownewRuntimeException(e);}}}

反序列化 person 对象

publicvoidtest4(){ObjectInputStreamois=null;try{Filefile=newFile("object1.dat");ois=newObjectInputStream(newFileInputStream(file));//2. 读取文件中的对象(或反序列化的过程)Personperson=(Person)ois.readObject();System.out.println(person);Personperson1=(Person)ois.readObject();System.out.println(person1);}catch(IOExceptione){thrownewRuntimeException(e);}catch(ClassNotFoundExceptione){thrownewRuntimeException(e);}finally{try{if(ois!=null)ois.close();}catch(IOExceptione){thrownewRuntimeException(e);}}}
http://www.jsqmd.com/news/892277/

相关文章:

  • 自制高选择性音频滤波器:从噪音中精准提取CW莫尔斯电码信号
  • 频谱分析仪精准选型指南:覆盖5G军工科研场景,国产替代降本增效 - 深度智识库
  • 收藏!小白程序员必看:5000万向量平滑迁移大模型实战指南(附回滚策略)
  • 2026年5月廊坊地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • 2026年5月荆州地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • GHelper AMD降压超频技术深度解析:华硕笔记本性能调优实战指南
  • 【仅限首批200位开发者】AI Agent物联网开发套件V2.3内测权限开放:含OPC UA/Modbus/TDengine原生Agent模板及联邦学习调度器
  • 前端工程师的焦虑与自救:转型AI工程师,收藏这份进阶指南
  • COMIF框架:区分侧信息类型,优化序列推荐中的融合策略
  • 2026好用的去水印小程序推荐,热门工具实测对比
  • 2026年5月通辽地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • 湖南AI搜索排名主流服务商决策参考 - 资讯速览
  • 2026年5月景德镇地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • 基于ESP32与太阳位置算法的智能光照控制器设计与实现
  • 2026年5月铜川地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • AI工具如何重构大宗商品风控体系:7个已被验证的落地场景与ROI测算模型
  • HiTS:分层文本引导的素描人脸精准上色与身份保持技术
  • 2026年5月阜阳地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • 2026免费视频去水印软件有哪些?一键去除视频水印软件推荐
  • 2026年5月九江地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • 马斯克放大招!xAI Grok新模型完成训练,编程工具Grok Build开启测试
  • 基于TL431与MOSFET的UF2烧录助手:解决RP2040开发板调试痛点
  • 期望值、方差与相关性:理解随机世界中的“平均未来”
  • 基于PIC单片机的低成本有线防盗报警器DIY:双回路动态检测与抗干扰设计
  • MECFormer:基于自编码器与Transformer的多曝光图像校正技术解析
  • 2026年5月铜陵地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • 2026年烟台口碑好的装修公司哪家专业?答案就在这里! - 资讯纵览
  • 2026年5月铜仁地区黄金回收白银铂金回收甄选门店推荐TOP1 地址及联系方式 - 五金回收
  • VirtualLab Fusion中的参数耦合
  • 基于复杂网络神经动力学的缺陷报告自动分派框架设计与实现