I/O流
null
流是一种顺序访问文件的方法。I/O流指代表不同类型源(例如磁盘文件)的输入源或输出目的地。爪哇。io包提供的类允许您在Unicode字符流和非Unicode文本的字节流之间进行转换。
流动 –一系列数据。 输入流: 从源读取数据。 输出流: 将数据写入目标。
字符流
在Java中,字符是使用Unicode约定存储的(参见 这 详细信息)。字符流自动允许我们逐个字符地读/写数据。例如,FileReader和FileWriter是用于从源读取和写入目标的字符流。
// Java Program illustrating that we can read a file in // a human readable format using FileReader import java.io.*; // Accessing FileReader, FileWriter, IOException public class GfG { public static void main(String[] args) throws IOException { FileReader sourceStream = null ; try { sourceStream = new FileReader( "test.txt" ); // Reading sourcefile and writing content to // target file character by character. int temp; while ((temp = sourceStream.read()) != - 1 ) System.out.println(( char )temp); } finally { // Closing stream as no longer in use if (sourceStream != null ) sourceStream.close(); } } } |
输出:
Shows contents of file test.txt
字节流
字节流逐字节(8位)处理数据。例如,FileInputStream用于从源读取,FileOutputStream用于写入目标。
// Java Program illustrating the Byte Stream to copy // contents of one file to another file. import java.io.*; public class BStream { public static void main(String[] args) throws IOException { FileInputStream sourceStream = null ; FileOutputStream targetStream = null ; try { sourceStream = new FileInputStream( "sorcefile.txt" ); targetStream = new FileOutputStream ( "targetfile.txt" ); // Reading source file and writing content to target // file byte by byte int temp; while ((temp = sourceStream.read()) != - 1 ) targetStream.write(( byte )temp); } finally { if (sourceStream != null ) sourceStream.close(); if (targetStream != null ) targetStream.close(); } } } |
什么时候使用字符流而不是字节流?
- 在Java中,字符是使用Unicode约定存储的。当我们想要处理文本文件时,字符流很有用。这些文本文件可以逐个字符进行处理。字符大小通常为16位。
何时在字符流上使用字节流?
- 面向字节的逐字节读取。字节流适合处理二进制文件等原始数据。
笔记:
- 字符流的名称通常以读写器结尾,字节流的名称以InputStream/OutputStream结尾
- 示例代码中使用的流是无缓冲流,效率较低。为了提高效率,我们通常将它们与缓冲读写器一起使用。我们将很快讨论使用BufferedReader/BufferedWriter(用于字符流)和BufferedInputStream/BufferedOutputStream(用于字节流)类。
- 如果不再使用,建议始终关闭该流。这确保了如果发生任何错误,流不会受到影响。
- 上述代码可能不会在在线编译器中运行,因为文件可能不存在。
本文由 莫希特·古普塔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END