字符流与字节流在Java IO中的应用与示例
版权申诉
165 浏览量
更新于2024-09-11
收藏 52KB PDF 举报
在Java编程中,输入/输出流(I/O Stream)是处理文件和其他数据源的重要工具。IO流主要分为两类:字符流和字节流,它们各自针对不同的数据类型和应用场景进行操作。
1. 字符流 (Character Streams)
- 适用于处理文本数据,特别是中文内容,因为字符流确保了文本的正确编码和读写。
- 读取 (Reading):
- 使用`FileReader`和`BufferedReader`组合。例如,以下代码展示了如何读取文本文件:
```
File file = new File("practice1.txt");
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
```
- 写入 (Writing):
- 使用`FileWriter`和`BufferedWriter`,如写入字符串到文件:
```
File file = new File("practice1.txt");
FileWriter fr = null;
BufferedWriter bw = null;
try {
fr = new FileWriter(file);
bw = new BufferedWriter(fr);
bw.write("hello,world!"); // 写入一行
bw.newLine(); // 插入换行符
bw.write("!Hello,World!"); // 写入另一行
bw.flush();
System.out.println("已结束");
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
e.printStackTrace();
}
```
2. 字节流 (Byte Streams)
- 字节流主要用于处理二进制数据,如图片、视频等,以及处理非文本内容。
- 数据写出 (Writing):
- 常用`FileOutputStream`进行文件操作,如将字节数组写入:
```
File file = new File("image.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
byte[] bytes = ...; // 图片或视频的字节数组
fos.write(bytes);
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
e.printStackTrace();
}
```
- 数据读入 (Reading):
- 使用`FileInputStream`配合`FileOutputStrea`m,如果数据以字节数组的形式存在,可以这样读取:
```
FileInputStream fis = null;
try {
fis = new FileInputStream("image.jpg");
byte[] bytes = new byte[(int) fis.available()];
fis.read(bytes);
// 处理字节数组
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
```
总结来说,字符流和字节流在Java I/O中扮演着至关重要的角色。字符流用于文本数据的处理,注重编码和格式,而字节流则处理原始二进制数据,如图片和视频。根据实际需求,选择合适的流类型,结合适当的异常处理,能够更有效地进行数据读写操作。
2016-10-28 上传
2020-11-11 上传
点击了解资源详情
2023-06-10 上传
2023-08-16 上传
2024-08-18 上传
2023-05-19 上传
2023-07-11 上传
2023-04-19 上传
weixin_38515897
- 粉丝: 2
- 资源: 961
最新资源
- C++标准程序库:权威指南
- Java解惑:奇数判断误区与改进方法
- C++编程必读:20种设计模式详解与实战
- LM3S8962微控制器数据手册
- 51单片机C语言实战教程:从入门到精通
- Spring3.0权威指南:JavaEE6实战
- Win32多线程程序设计详解
- Lucene2.9.1开发全攻略:从环境配置到索引创建
- 内存虚拟硬盘技术:提升电脑速度的秘密武器
- Java操作数据库:保存与显示图片到数据库及页面
- ISO14001:2004环境管理体系要求详解
- ShopExV4.8二次开发详解
- 企业形象与产品推广一站式网站建设技术方案揭秘
- Shopex二次开发:触发器与控制器重定向技术详解
- FPGA开发实战指南:创新设计与进阶技巧
- ShopExV4.8二次开发入门:解决升级问题与功能扩展