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

从字节到对象的漂流---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 进行编码转换🔄
注意不同平台默认编码差异🧭

相关文章:

  • (46)课68:查看索引 SHOW INDEX FROM 表名;删除索引 DROP INDEX index_name ON 表名;
  • 青藏高原ASTER_GDEM数据集(2011)
  • Office 365下载安装教程(超详细图文教程)从零开始的完整安装指南
  • Nuttx之mm_extend
  • ISO/IEC 14443 防碰撞协议 Type A Type B
  • NIFI在Linux系统中的系统配置最佳实践(性能调优)
  • Shuffle流程
  • 【Linux系统编程】System V
  • 大模型呼叫系统——重塑学校招生问答,提升服务效能
  • 离线部署openstack 2024.1 neutron
  • 曼昆《经济学原理》第九版 第十八章生产要素市场
  • 离线部署openstack 2024.1 nova
  • 火山引擎大模型系列都有什么内容
  • Java高频面试之并发编程-27
  • Ubuntu24.04 onnx 模型转 rknn
  • 大语言模型智能体开发的技术框架与应用前景
  • 频域分析和注意力机制
  • 华测CGI-430配置
  • 离线部署openstack 2024.1 keystone
  • 计组刷题日记(1)
  • 免费的推广渠道有哪些/优化seo方案
  • 文件备案网站建设方案/一般的电脑培训班要多少钱
  • 网站内容的编辑和更新怎么做的/上海怎么做seo推广
  • 专业重庆房产网站建设/最简单的网页制作
  • 网站目录做二级域名/武汉seo管理
  • 网站制作怎样盈利/多层次网络营销合法吗