字符流与字节流在Java IO中的应用与示例

版权申诉
0 下载量 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中扮演着至关重要的角色。字符流用于文本数据的处理,注重编码和格式,而字节流则处理原始二进制数据,如图片和视频。根据实际需求,选择合适的流类型,结合适当的异常处理,能够更有效地进行数据读写操作。