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

从字节到对象的漂流---JavaIO流篇

📚 一、IO流初探:数据的魔法传送门 🔮


💡 流是什么?
在Java世界里,IO流就像是一个神奇的数据搬运工🚚,它能把数据从一个地方传送到另一个地方。

就像哈利波特里的“呼噜网”一样,可以把人从一个壁炉传送到另一个壁炉🔥。

🧭 分类地图 🗺️

          ┌───────────────┐│    抽象基类    │└───────────────┘▲┌────────┴────────┐│                 │字节流InputStream    OutputStream ⚡(适合二进制文件)│                 │字符流Reader        Writer 📝(适合文本文件)


💾 二、字节流篇:最原始的力量 ⚡


1. FileInputStream & FileOutputStream
像两个勤劳的小精灵🧚,一个负责把文件内容一点点搬出来,一个负责把内容放回去📦。

示例代码:

try (FileInputStream fis = new FileInputStream("input.txt");FileOutputStream fos = new FileOutputStream("output.txt")) {int data;while ((data = fis.read()) != -1) {  // 👀 读取一个字节fos.write(data);  // ✍️ 写入一个字节}
} catch (IOException e) {System.err.println("Oops! 出错了!💥" + e.getMessage());
}


2. BufferedInputStream & BufferedOutputStream
带背包的小精灵🎒,一次可以搬运更多数据,效率提升🚀!

示例代码:

try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {byte[] buffer = new byte[1024];  // 背包容量1024字节🎒int bytesRead;while ((bytesRead = bis.read(buffer)) != -1) {bos.write(buffer, 0, bytesRead);  // 搬运整个背包内容📦}
} catch (IOException e) {System.out.println("传输失败!⚠️ " + e.getMessage());
}


📝 三、字符流篇:专为文字设计的搬运术 📖


FileReader & FileWriter
它们懂中文、英文、emoji 😄,能处理各种语言的文本。

示例代码:

try (FileReader reader = new FileReader("input.txt");FileWriter writer = new FileWriter("output.txt")) {int charCode;while ((charCode = reader.read()) != -1) {writer.write(charCode);  // 写入字符✍️}
} catch (IOException e) {System.out.println("哎呀,写崩了!😵‍💫");
}


BufferedReader & BufferedWriter
超级高效的图书馆管理员📚,可以一次读一行!

示例代码:

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {String line;while ((line = br.readLine()) != null) {bw.write(line);bw.newLine();  // 换行✅}
} catch (IOException e) {System.out.println("读取失败,是不是书太厚了?📖💔");
}


🧠 四、对象流篇:让对象飞起来!✈️

ObjectOutputStream & ObjectInputStream
可以直接把对象打包发送📦,还能还原回来🔄!

示例代码:

// 写入对象
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {Person person = new Person("张三", 25);oos.writeObject(person);  // 发射对象导弹🚀
} catch (IOException e) {System.out.println("对象发射失败!💣");
}// 读取对象
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {Person person = (Person) ois.readObject();System.out.println("接收到的对象:" + person);
} catch (IOException | ClassNotFoundException e) {System.out.println("对象接收失败,是不是掉沟里了?🕳️");
}


📌 注意事项:

类必须实现 Serializable 接口🧾
可以用 transient 标记不想被保存的字段🚫
建议手动定义 serialVersionUID🔒
🔁 五、转换流:字节与字符之间的翻译官 🧑‍⚖️
InputStreamReader & OutputStreamWriter
相当于中英翻译器🌍,让不同语言之间沟通无障碍🗣️

示例代码:

try (InputStreamReader isr = new InputStreamReader(new FileInputStream("input.txt"), StandardCharsets.UTF_8);OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output.txt"), StandardCharsets.UTF_8)) {char[] buffer = new char[1024];int charsRead;while ((charsRead = isr.read(buffer)) != -1) {osw.write(buffer, 0, charsRead);  // 翻译并写入✍️}
} catch (IOException e) {System.out.println("翻译出错啦!❌" + e.getMessage());
}


🖨️ 六、打印流:输出界的艺术家 🎨


PrintStream & PrintWriter
不仅能写,还能格式化输出🎨,让你的输出更美观✨

示例代码:

try (PrintWriter pw = new PrintWriter(new FileWriter("output.txt"))) {pw.println("Hello World 🌍");  // 输出一行pw.printf("姓名: %s, 年龄: %d%n", "张三", 25);  // 格式化输出
} catch (IOException e) {System.out.println("打印机卡纸了!🖨️💢");
}


🔍 七、随机访问文件:想跳哪就跳哪的超能力 🚪


RandomAccessFile
像时空穿梭机一样,可以任意定位文件位置⏳

示例代码:

try (RandomAccessFile raf = new RandomAccessFile("data.txt", "rw")) {raf.writeInt(123);       // 写入整数🔢raf.writeUTF("张三");    // 写入字符串📝raf.seek(0);             // 回到开头🔚int id = raf.readInt();         // 读取整数📊String name = raf.readUTF();    // 读取字符串🔍System.out.println("ID: " + id + ", Name: " + name);
} catch (IOException e) {System.out.println("文件穿越失败!🌀");
}


🚀 八、NIO新纪元:更快更强的新一代传输技术 🚀


FileChannel & Path/Files
新一代的高速通道🚄,传输速度更快,功能更强大💪

文件复制示例:

try (FileInputStream fis = new FileInputStream("source.txt");FileOutputStream fos = new FileOutputStream("target.txt")) {FileChannel sourceChannel = fis.getChannel();FileChannel targetChannel = fos.getChannel();sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);  // 高速传输⚡
} catch (IOException e) {System.out.println("NIO传输失败,是不是网络不好?📶");
}


🧰 九、工具类封装:懒人必备神器 🛠️


文件拷贝工具 FileUtils

public class FileUtils {public static void copyFile(String sourcePath, String destPath) {try (FileInputStream fis = new FileInputStream(sourcePath);FileOutputStream fos = new FileOutputStream(destPath);FileChannel sourceChannel = fis.getChannel();FileChannel destChannel = fos.getChannel()) {sourceChannel.transferTo(0, sourceChannel.size(), destChannel);} catch (IOException e) {System.out.println("文件复制失败!📄❌");}}
}

十、最佳实践与避坑指南 🚧


✅ 异常处理技巧
使用 try-with-resources 自动关闭资源🗑️
捕获具体异常类型而不是笼统的 Exception 🎯
记录详细的错误信息以便排查问题🔍
⚡ 性能优化建议
使用缓冲流(BufferedXXX) 提升效率🏎️
合理设置缓冲区大小(推荐 1KB~8KB)📦
对大文件使用 NIO 提高性能🚀
🧹 资源管理守则
确保所有流都正确关闭🧹
多层嵌套时只需关闭外层流🚪
使用 finally 或 try-with-resources 关闭资源🔐
🌏 编码处理要点
明确指定编码格式(如 UTF-8)📜
使用 InputStreamReader/OutputStreamWriter 进行编码转换🔄
注意不同平台默认编码差异🧭

http://www.xdnf.cn/news/13689.html

相关文章:

  • 5. 相机拍摄简单构图
  • 1.9 Express
  • Flutter 常用组件详解:Text、Button、Image、ListView 和 GridView
  • c++中main函数执行完后还执行其它语句吗?
  • FreeRTOS互斥量
  • 面向异构系统的多面体编译优化关键技术研究——李颖颖博士
  • Linux 任务调度策略
  • 一数一源一标准的补充
  • 论文阅读:强化预训练
  • 强化学习入门:交叉熵方法实现CartPole智能体
  • 一个超强的推理增强大模型,开源了,本地部署
  • 跨网数据摆渡系统:破解数据流通难题的“标准答案”
  • 别人如何访问我的内网呢? 设置让外网访问内网本地服务器和指定端口应用的几种方式
  • 曼昆《经济学原理》第九版 第十八章生产要素市场
  • Vue Electron 使用来给若依系统打包成exe程序,出现登录成功但是不跳转页面(已解决)
  • Vue 中 data 选项:对象 vs 函数
  • Rust 学习笔记:通过异步实现并发
  • 【题解-洛谷】P2935 [USACO09JAN] Best Spot S
  • 算法训练第十五天
  • docker推荐应用汇总及部署实战
  • ComfyUI-安装
  • 不装 ROS 也能用 PyKDL!使用kdl_parser解析URDF并进行IK
  • Linux-进程间的通信
  • 大数据服务器的特点都指什么?
  • Python----OpenCV(图像处理——边界填充、图像融合、图像阈值、深拷贝与浅拷贝)
  • 零基础学前端-传统前端开发(第三期-CSS介绍与应用)
  • 【报错】【docker】write /opt/test/Model.gguf: no space left on device
  • 飞书多维表格利用 Amazon Bedrock AI 能力赋能业务
  • GlusterFS概述
  • 鸿蒙新闻应用全链路优化实践:从内核重构到体验革新