本文共 2075 字,大约阅读时间需要 6 分钟。
流是Java I/O体系中的核心概念,它是数据在程序中以流的方式进行读取和写入的载体。在现代计算机系统中,所有的数据存储和传输都以流的形式进行处理,程序需要通过输入流获取数据,通过输出流将数据保存下来。
程序中的输入输出操作都以流的形式进行,可以分为字节流和字符流两大类:
字节流:
InputStream
和 OutputStream
类完成输入输出操作。byte
(8位字节)。字符流:
Reader
和 Writer
类完成输入输出操作。char
(16位 Unicode 字符)。Java 提供了 java.io
包,包含输入输出操作的核心抽象类和具体实现类。这些类分为:
InputStream
和 OutputStream
,处理任意类型的二进制数据。Reader
和 Writer
,处理字符或字符串数据。byte
为单位操作,字符 flow 以 char
为单位。// 写操作示例public class Test11 { public static void main(String[] args) throws IOException { File f = new File("d:" + File.separator + "test.txt"); OutputStream out = new FileOutputStream(f); String str = "Hello World"; byte[] b = str.getBytes(); out.write(b); out.close(); }}// 追加写操作示例public class Test17 { public static void main(String[] args) throws IOException { File f = new File("d:" + File.separator + "test.txt"); Writer out = new FileWriter(f, true); String str = "\r\nHello World"; out.write(str); out.close(); }}
InputStream.read()
方法可以读取单个字节。返回值为 int
,其中 0-255
表示有效字节,-1
表示末尾。FileInputStream
reader 读取文件的全部字节,可以通过滑动窗口逐读,每次读取指定数量的字节。public class Test13 { public static void main(String[] args) throws IOException { File f = new File("d:" + File.separator + "test.txt"); FileInputStream fin = new FileInputStream(f); byte[] b = new byte[f.length()]; byte temp; int len = 0; while ((temp = fin.read()) != -1) { b[len++] = temp; } fin.close(); System.out.println(new String(b)); }}
BufferedInputStream
和 BufferedWriter
)来提升输入输出效率。close()
方法关闭输入输出流资源,以防止资源泄漏。总的来说,选择字节流还是字符流取决于具体的数据类型。在处理二进制数据(如图片、音频)时,字节流是更优选择;而在处理文本数据(如文档、代码文件)时,字符流更适合。掌握这两种流的使用方法,是Java编程中非常重要的技能。
转载地址:http://ufixz.baihongyu.com/