Java中字节流和字符流类的区别?
Java提供I/O流来读写数据,其中流代表输入源或输出目标,可以是文件、I/O设备或其他程序等。
根据它们处理的数据,流有两种类型:
- 字节流 - 这些流以字节(8位)处理数据,即字节流类读写8位数据。使用这些流,您可以存储字符、视频、音频、图像等。
- 字符流 - 这些流以16位Unicode处理数据。使用这些流,您只能读写文本数据。
Reader和Writer类(抽象类)是所有字符流类的超类:用于读写字符流的类。
而InputStream和OutputStream类(抽象类)是所有输入/输出流类的超类:用于读写字节流的类。
下图说明了Java中所有输入和输出流(类)。
输入/输出流和Reader/Writer的区别
它们的主要区别在于输入/输出流类读写字节流数据,而Reader/Writer类处理字符。
输入/输出流类的方法接受字节数组作为参数,而Reader/Writer类的方法接受字符数组作为参数。
Reader/Writer类处理所有Unicode字符,方便国际化,比输入/输出流更高效。
因此,除非您处理像图像这样的二进制数据,否则建议使用Reader/Writer类。
输入/输出流示例
下面的Java程序使用FileInputStream从特定文件读取数据,并使用FileOutputStream将其写入另一个文件。
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class IOStreamsExample { public static void main(String args[]) throws IOException { //Creating FileInputStream object File file = new File("D:/myFile.txt"); FileInputStream fis = new FileInputStream(file); byte bytes[] = new byte[(int) file.length()]; //Reading data from the file fis.read(bytes); //Writing data to another file File out = new File("D:/CopyOfmyFile.txt"); FileOutputStream outputStream = new FileOutputStream(out); //Writing data to the file outputStream.write(bytes); outputStream.flush(); System.out.println("Data successfully written in the specified file"); } }
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
输出
Data successfully written in the specified file
Reader/Writer流示例
下面的Java程序使用FileReader从特定文件读取数据,并使用FileWriter将其写入另一个文件。
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class IOStreamsExample { public static void main(String args[]) throws IOException { //Creating FileReader object File file = new File("D:/myFile.txt"); FileReader reader = new FileReader(file); char chars[] = new char[(int) file.length()]; //Reading data from the file reader.read(chars); //Writing data to another file File out = new File("D:/CopyOfmyFile.txt"); FileWriter writer = new FileWriter(out); //Writing data to the file writer.write(chars); writer.flush(); System.out.println("Data successfully written in the specified file"); } }
输出
Data successfully written in the specified file
广告