IO stream [Four abstract classes of IO in Java, detailed explanation of commonly used streams, buffered byte stream, file character stream, buffered character stream] (2) - comprehensive detailed explanation (learning summary --- from entry to deepening)

Table of contents

 Four abstract classes of IO in Java

Detailed explanation of common streams 

 buffer byte stream

 file character stream

buffered character stream


 Four abstract classes of IO in Java

 The InputStream/OutputStream and Reader/writer classes are the abstract parent classes of all IO stream classes. It is necessary for us to briefly understand the functions of these four abstract classes. Then, familiarize yourself with the related usage through their concrete subclasses.

 InputStream

This abstract class is the parent class of all classes representing byte input streams. InputSteam is an abstract class, it cannot be instantiated. The reading of data needs to be implemented by its subclasses. Depending on the node, it derives different node stream subclasses. The streams inherited from InputSteam are used to input data into the program, and the unit of data is byte (8 bit).

Common methods:

 OutputStream

This abstract class is the parent class of all classes representing byte output streams. An output stream takes output bytes and sends those bytes to some destination.

Common methods:

Reader

Reader is an abstract class for reading character streams, and the data unit is characters.

Writer

The character stream abstract class used by Writer for output, and the data unit is character.

Detailed explanation of common streams 

file byte stream

 FileInputStream    reads files by bytes and is suitable for reading all types of files (images, videos, text files, etc.).

FileOutputStream writes data to files by byte, suitable for all types of files (images, videos, text files, etc.).

 FileInputStream file input byte stream

public class TestFileInputStream {
    public static void main(String[] args) {
        //使用try-with-resource方式关闭资源。
        //在try中打开资源,不需要在代码中添加finally块关闭资源。
        try(FileInputStream fis = new FileInputStream("d:/a.txt");){
            StringBuilder sb = new StringBuilder();
            int temp=0;
            while((temp = fis.read()) != -1)
           {
                sb.append((char) temp);
           }
              System.out.println(sb);
       }catch(Exception e){
            e.printStackTrace();
       }
   }

FileOutputStream file output byte stream

public class TestFileOutputStream {
    public static void main(String[] args) {
        String str = "Old Lu";
        // true表示内容会追加到文件末尾;false表示重写整个文件内容。
        try(FileOutputStream fos = new
             FileOutputStream("d:/a.txt",true)){
            //将整个字节数组写入到文件中。
            fos.write(str.getBytes());
           //将数据从内存中写入到磁盘中。
           fos.flush();
       }catch (IOException e){
            e.printStackTrace();
       }
   }
}

Improve read and write efficiency through byte buffers

 By creating a byte array of a specified length as a buffer, the read and write efficiency of the IO stream is improved. This method is suitable for buffer definition when reading large files. Note: The length of the buffer must be an integer power of 2. In general, the length of 1024 is more appropriate.

public class TestFileByteBuffer{
    public static void main(String[] args) {
        long time1 = System.currentTimeMillis();
        copyFile("d:/1.jpg", "d:/2.jpg");
        long time2 = System.currentTimeMillis();
        System.out.println(time2 - time1);
   }
    /**
     *
     * @param src 源文件
     * @param desc 目标文件
     */
    public static void copyFile(String src,String desc){
       //“后开的先关闭!”按照他们被创建顺序的逆序来关闭
       try(FileInputStream fis = new FileInputStream(src);
           FileOutputStream fos = new FileOutputStream(desc)){
           //创建一个缓冲区,提高读写效率
            byte[] buffer = new byte[1024];
            int temp = 0;
            while ((temp = fis.read(buffer)) != -1){
          //将缓存数组中的数据写入文件中,注意:写入的是读取的真实长度;
            fos.write(buffer,0,temp);
           }
            //将数据从内存中写入到磁盘中。
           fos.flush();
       }
        catch (IOException e) {
            e.printStackTrace();
       }
   }
}

 Note that when using byte buffers, we need to pay attention to:

1. In order to reduce the number of reads and writes to the hard disk and improve efficiency, a cache array is usually set. Correspondingly, the method used for reading is: read(byte[] b); the method for writing is: write(byte[ ] b, int off, int length)

2. If multiple streams are encountered in the program, each stream must be closed separately to prevent the situation that other streams cannot be closed after one of the streams is abnormal.

 buffer byte stream

 The Java buffer stream itself does not have the function of reading and writing IO streams, but adding buffering functions to other streams (node ​​streams or other processing streams) to improve efficiency, just like wrapping other streams, so A buffered stream is a processing stream (wrapper stream). The two streams, BufferedInputStream and BufferedOutputStream, are buffered byte streams, which improve the efficiency of operating streams by internally caching arrays.

Efficient copying of files using buffered streams

Below we realize the copying of a file in two ways (ordinary file byte stream and buffered file byte stream) to experience the benefits of buffered stream.

public class TestFileBufferStream {
    public static void main(String[] args) {
        long time1 = System.currentTimeMillis();
        copyFile("d:/1.jpg","d:/2.jpg");
        long time2 = System.currentTimeMillis();
        System.out.println(time2 - time1);
   }
    public static void copyFile(String source,String destination){
            //实例化节点流
        try(FileInputStream fis = new FileInputStream(source);
            FileOutputStream fos = new FileOutputStream(destination);
            //实例化处理流
            BufferedInputStream bis = new BufferedInputStream(fis);
            BufferedOutputStream bos = new BufferedOutputStream(fos)){
            int temp = 0;
            while ((temp = bis.read()) !=-1){
                bos.write(temp);
           }
            bos.flush();
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

 Notice

1. When closing the stream, the outermost packaging stream should be closed first, that is, "the one opened last is closed first".

2. The size of the cache area is 8192 bytes by default, and you can also use other construction methods to specify the size yourself.

 file character stream

 The file byte stream introduced earlier can handle all files. If we are dealing with text files, we can also use the file character stream, which operates in units of characters.

file character input stream

public class TestFileReader {
    public static void main(String[] args) {
        //创建文件字符输入流对象
        try(FileReader fr = new FileReader("d:/a.txt")){
            StringBuilder sb = new StringBuilder();
        //读取文件
           int temp = 0;
           while((temp = fr.read()) != -1){
               sb.append((char)temp);
           }
            System.out.println(sb);
       }catch (IOException e){
            e.printStackTrace();
       }
   }
}

file character output stream

public class TestFileWriter {
    public static void main(String[] args) {
        //创建文件字符输出流对象
        try(FileWriter fw = new FileWriter("d:/aa.txt")){
            fw.write("您好尚\r\n");
            fw.write("您好Old Lu\r\n");
            fw.flush();
       }catch (IOException e){
            e.printStackTrace();
       }
   }
}

buffered character stream

 BufferedReader/BufferedWriter adds a cache mechanism, which greatly improves the efficiency of reading and writing text files.

character input buffer stream 

BufferedReader is a buffered stream object for character input streams, which provides a more convenient method of reading line by line: readLine(); When using character streams to read text files, we can use this method to read in line units.

public class TestBufferedReader {
    public static void main(String[] args) {
            //创建文件字符输入流对象
        try(FileReader fr = new FileReader("d:/aa.txt");
            //创建字符缓冲处理流。缓冲区默认大小为8192个字符。
            BufferedReader br = new BufferedReader(fr)){
            //操作流
            String temp = "";
            //readLine():读取一行文本。
            while((temp = br.readLine()) != null){
                System.out.println(temp);
           }
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

character output buffered stream

BufferedWriter is a buffer stream object for the character output stream, in the character output buffer stream you can use the newLine(); method to implement newline processing.

public class TestBufferedWriter {
    public static void main(String[] args) {
  //创建文件字符输出流对象
        try(FileWriter fw = new FileWriter("d:/sxt.txt");
            //创建字符输出缓冲流对象
            BufferedWriter bw = new BufferedWriter(fw)){
            //操作缓冲流
            bw.write("您好尚像素");
            bw.write("您好Oldlu");
            //换行
            bw.newLine();
            bw.write("何以解忧");
            bw.newLine();
            bw.write("唯有学堂");
            bw.flush();
       }catch (IOException e){
            e.printStackTrace();
       }
   }
}

Notice

The readLine() method is a method of BufferedReader, which can read text files more conveniently. newLine() method The method of BufferedWriter, you can use the newLine() method to wrap.

 Add line numbers to the contents of the file

public class TestLineNumber {
    public static void main(String[] args) {
            //创建字符输入缓冲流与文件字符输入流
            try(BufferedReader br = new BufferedReader(new FileReader("d:/sxt.txt"));
            //创建字符输出缓冲流与文件字符输出流
            BufferedWriter bw = new BufferedWriter(new FileWriter("d:/sxt2.txt"))){
            String temp ="";
            //定义序号变量
            int i = 1;
            while((temp = br.readLine()) != null){
                //将读取到的内容添加序号,并输出到指定文件中。
                bw.write(i+","+temp);
                //换行处理
                bw.newLine();
                //序号变量累加
                i++;
           }
            //刷新
            bw.flush();
       }catch(IOException e){
            e.printStackTrace();
       }
   }
}

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131647332