字节流和字符流区别
- 使用字节流操作非文本文件:.jpg, .mp3 , .mp4 , .doc , .ppt
- 文本文件:.txt .java .c .cpp ---》建议使用字符流操作
读取案例1(此处关闭流均已省略)
| fileReader = new FileReader(file1); |
| fileWriter = new FileWriter(file); |
| char[] chars1 = new char[5]; |
| int i = fileReader.read(chars1); |
| while (i != -1) { |
| |
| |
| fileWriter.write(chars1,0,i); |
| |
| i = fileReader.read(chars1); |
| |
| |
| |
读取案例2(此处关闭流均已省略)
| File file = new File("D://IDEA/Picture.jpg"); |
| File file2 = new File("D://IDEA/PictureCopy.jpg"); |
| |
| FileInputStream fileInputStream =new FileInputStream(file); |
| FileOutputStream fileOutputStream = new FileOutputStream(file2); |
| |
| byte []by = new byte[1024*8]; |
| |
| int len = fileInputStream.read(by); |
| while (len!=-1){ |
| fileOutputStream.write(by,0,len); |
| len = fileInputStream.read(by); |
| } |
利用缓冲区,字节流
| package com.IO; |
| import java.io.*; |
| public class Buffinput { |
| public static void main(String[] args) { |
| //源文件,目标文件 |
| File file = new File("D://IDEA/Picture.jpg"); |
| File fileCopy = new File("D://IDEA/PictureType.jpg"); |
| //创建字节流 |
| BufferedInputStream buffinput = null; |
| BufferedOutputStream buffOutput =null; |
| try { |
| |
| FileInputStream fileInputStream = new FileInputStream(file); |
| FileOutputStream fileOutputStream = new FileOutputStream(fileCopy); |
| //利用缓冲区:处理流BufferedInputStream;BufferedOutputStream |
| buffinput = new BufferedInputStream(fileInputStream);//默认缓存区大写8192 |
| buffOutput =new BufferedOutputStream(fileOutputStream); |
| //利用缓冲数组: |
| byte []by = new byte[1028*6]; |
| int len = buffinput.read(by); |
| while (len!=-1){ |
| buffOutput.write(by,0,len); |
| len = buffinput.read(by); |
| } |
| } catch (FileNotFoundException e) { |
| e.printStackTrace(); |
| } catch (IOException e) { |
| e.printStackTrace(); |
| }finally { |
| try { |
| if (buffOutput != null) { |
| buffOutput.close(); |
| } |
| |
| } catch (IOException e) { |
| e.printStackTrace(); |
| } |
| try { |
| if(buffinput!=null){ |
| buffinput.close(); |
| } |
| } catch (IOException e) { |
| e.printStackTrace(); |
| } |
| } |
| |
| } |
| } |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!