3 core class library - IO

Keywords: Java

1, Overview of IO

  • IO stream overview
    • This data transmission operation can be regarded as a data flow, which is divided into Input and Output according to the flow direction
    • IO operations in Java mainly refer to the use of some common classes under the java.io package. These common classes are used to read (Input) and write (Output) data
  • Classification of IO streams:
    • According to the direction of flow, it can be divided into input flow and output flow
    • According to the flowing data type, it can be divided into byte stream and character stream

-How to judge output stream or input stream?
Output stream and input stream are relative to memory. Output from memory is output, and input into memory is input

  • Byte stream:
    •      -   Input stream :   InputStream
      
    •      -   Output stream :   OutputStream
      
  • Character stream:
  • Character stream = byte stream + encoding table
    •      -   Input stream :   Reader
      
    •      -   Output stream :   Writer
      
  • All bytes:
    •  Any data in the computer(text,picture,video,Music, etc)Are stored in binary form.
      
    •  In data transmission, they are also stored in binary form.
      

 *   Absolute path: a complete path, starting with a drive letter, for example F://aaa.txt
 *   Relative path: a simplified path that does not begin with a drive letter,for example//aaa.txt//b.txt

2, OutputStream

  • The java.io.OutputStream abstract class is a superclass (parent class) representing all classes of byte output stream. It writes the specified byte information to the destination. It defines the basic common function methods of byte output stream.
  • Basic common function methods of byte output stream (subclasses will share the following methods):
    • 1. public void close(): close this output stream and release any system resources associated with this stream.
      2. public void flush(): flushes this output stream and forces any buffered output bytes to be written out.
      3. public void write(byte[] b): write b.length bytes from the specified byte array to this output stream.
      4. public void write(byte[] b, int off, int len): writes len bytes from the specified byte array and outputs them to this output stream starting from offset off. That is, read from off bytes to len bytes
      5. public abstract void write(int b): outputs the specified bytes to the stream.
  • FileOutputStream class
    OutputStream has many subclasses. Let's start with the simplest subclass, FileOutputStream. Look at the name to know that it is a file output stream, which is used to write data to a file.
  • Construction method:
    • 1. public FileOutputStream(File file): creates an object for parameters based on the File object.
      2. public FileOutputStream(String name): creates an object for the parameter based on the name string. (common)
  •  FileOutputStream outputStream = new FileOutputStream("abc.txt");
    
public class FileOutputStreamConstructor throws IOException {
    public static void main(String[] args) {
   	 	// Create a stream object using a File object
        File file = new File("G:\\Automatically created folders\\a.txt");
        FileOutputStream fos = new FileOutputStream(file);
      
        // Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("G:\\b.txt");
    }
}
  • When creating a stream object, you must pass in a file path directly or indirectly. For example, now we create a FileOutputStream stream object. If there is no file in this path, the file will be created. If there is this file, the data of this file will be cleared.
  • FileOutputStream writes out byte data
  • public void write(int b)
    public void write(byte[] b)
    public void write(byte[] b,int off,int len) / / starting from the off index, len bytes
public class IoWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt");     
      	// Write data
      	fos.write(97); // Write the first byte
      	fos.write(98); // Write the second byte
      	fos.write(99); // Write the third byte
      	// close resource
        fos.close();//After the stream operation is completed, the system resources must be released!!!!!!!!!
    }
}
Output results:
abc
public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt");     
      	// Convert string to byte array
      	byte[] b = "one two three four five".getBytes();
      	// Write out byte array data
      	fos.write(b);
      	// close resource
        fos.close();
    }
}
Output results:
one two three four five
public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt");     
      	// Convert string to byte array
      	byte[] b = "abcde".getBytes();
		// Write 2 bytes starting from index 2. Index 2 is c, two bytes, that is, cd.
        fos.write(b,2,2);
      	// close resource
        fos.close();
    }
}
Output results:
cd
  • public FileOutputStream(File file, boolean append)
    public FileOutputStream(String name, boolean append)
    For these two construction methods, a boolean value needs to be passed in the second parameter. true means to append data, and false means not to append, that is, to empty the original data. The output stream object created in this way can specify whether to append
public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt",true);     
      	// Convert string to byte array
      	byte[] b = "abcde".getBytes();
		// Write 2 bytes starting from index 2. Index 2 is c, two bytes, that is, cd.
        fos.write(b);
      	// close resource
        fos.close();
    }
}
Before file operation: cd
 After file operation: cdabcde
public class FOSWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt");  
      	// Define byte array
      	byte[] words = {97,98,99,100,101};
      	// Traversal array
        for (int i = 0; i < words.length; i++) {
          	// Write a byte
            fos.write(words[i]);
          	// Write a newline and convert the newline symbol into an array
            fos.write("\r\n".getBytes());
        }
      	// close resource
        fos.close();
    }
}

Output results:
a
b
c
d
e

3, InputStream

In fact, the usage method is similar to that of the output stream, which is directly explained in the code:

public class FileInputStreamConstructor throws IOException{
    public static void main(String[] args) {
   	 	// Create a stream object using a File object
        File file = new File("a.txt");
        FileInputStream fos = new FileInputStream(file);
      
        // Create a stream object with a file name
        FileInputStream fos = new FileInputStream("b.txt");
    }
}
  • FileInputStream reads byte data: the read method can read one byte of data at a time, promote it to int type, read it to the end of the file, and return - 1
public class FISRead {
    public static void main(String[] args) throws IOException{
      	// Create a stream object with a file name
       	FileInputStream fis = new FileInputStream("read.txt");//The content in the read.txt file is abcde
      	// Read data and return a byte
        int read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
      	// Read to the end and return - 1
       	read = fis.read();
        System.out.println( read);
		// close resource
        fis.close();
    }
}
Output results:
a
b
c
d
e
-1
  • Through loop optimization:
public class FISRead {
    public static void main(String[] args) throws IOException{
      	// Create a stream object with a file name
       	FileInputStream fis = new FileInputStream("read.txt");
      	// Define variables and save data
        int b ;
        // Cyclic reading
        while ((b = fis.read())!=-1) {//You can also write an endless loop
            System.out.println((char)b);
        }
		// close resource
        fis.close();
    }
}
Output results:
a
b
c
d
e
  • Actual writing method in development:
package io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class input2 {
    public static void main(String args[]){
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream("a.txt");
            int len = 0 ;
            byte[] bys = new byte[1024];
            while ((len = inputStream.read(bys)) != -1) {
                System.out.println(new String(bys,0,len));
            }
        
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

4, Reader

  • The java.io.Reader abstract class is a super class (parent class) of all classes of the character input stream, which can read character information into memory. It defines the basic common function method of character input stream.
  • method:
  • 1. public void close(): close the flow and release any system resources associated with the flow.
    2. public int read(): reads a character from the input stream.
    3. public int read(char[] cbuf): read some characters from the input stream and store them in the character array cbuf
  • FileReader class
    The java.io.FileReader class is a convenient class for reading character files. The system default character encoding and default byte buffer are used during construction
    • Construction method:
      1. FileReader (File): create a new FileReader and give the File object to be read.
      2. FileReader(String fileName): create a new FileReader and give the string name of the file to be read.
public class FileReaderConstructor throws IOException{
    public static void main(String[] args) {
   	 	// Create a stream object using a File object
        File file = new File("a.txt");
        FileReader fr = new FileReader(file);
      
        // Create a stream object with a file name
        FileReader fr = new FileReader("b.txt");
    }
}

  • FileReader reads character data
public class FRRead {
    public static void main(String[] args) throws IOException {
      	// Create a stream object with a file name
       	FileReader fr = new FileReader("a.txt");
      	// Define variables and save data
        int b ;
        // Cyclic reading
        while ((b = fr.read())!=-1) {
            System.out.println((char)b);
        }
		// close resource
        fr.close();
    }
}

5, Writer

  • The java.io.Writer abstract class is the superclass (parent class) of all classes of the character output stream, which writes the specified character information to the destination. It also defines the basic common function method of character output stream
  • Basic common function methods of character output stream:
    1. void write(int c) writes a single character.
    2. void write(char[] cbuf) writes to the character array.
    3. abstract void write(char[] cbuf, int off, int len) writes a part of the character array, the start index of the off array, and the number of characters written by Len.
    4. void write(String str) writes a string.
    5. void write(String str, int off, int len) writes a part of the string, the start index of the off string, and the number of characters written by Len.
    6. void flush() flushes the buffer of the stream.
    7. void close() closes the stream, but first refreshes it.
  • FileWriter class
    The java.io.FileWriter class is a convenient class for writing characters to files. The system default character encoding and default byte buffer are used during construction.
    *Construction method:
    1. FileWriter (File): create a new FileWriter and give the File object to be read.
    2. FileWriter(String fileName): create a new FileWriter and give the name of the file to be read.
public class FileWriterConstructor {
    public static void main(String[] args) throws IOException {
   	 	// First: create a stream object using a File object
        File file = new File("a.txt");
        FileWriter fw = new FileWriter(file);
      
        // Second: create a stream object with a file name
        FileWriter fw = new FileWriter("b.txt");
    }
}

  • FileWriter writes out data
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileWriter fw = new FileWriter("fw.txt");     
      	// Write data
      	fw.write(97); // Write the first character
      	fw.write('b'); // Write the second character
      	fw.write('C'); // Write the third character
      	
        //When closing resources, it is different from FileOutputStream. If it is not closed, the data is only saved to the buffer, not to the file.
        // fw.close();
    }
}
Output results:
abC

When closing resources, it is different from FileOutputStream. If it is not closed, the data is only saved to the buffer, not to the file.

6, Flush

  • Flush: flush the buffer, and the stream object can continue to be used.
    close: flush the buffer first, and then notify the system to release resources. Stream objects can no longer be used.
public class FlushDemo {
    public static void main(String[] args) throws Exception {

        //This is to save the read content in another file

        //The source is the input stream [read stream] to read the a.txt file
        FileReader fr=new FileReader("a.txt");  //The a.txt file must exist, otherwise FileNotFoundException is reported
        //The destination is the output stream
        FileWriter fw=new FileWriter("b.txt");  //The system will automatically create b.txt because it is an output stream!
        int len;
        while((len=fr.read())!=-1){
           fw.write(len);
        }
    fr.close();
    fw.flush();
    fw.close();
}
}
  • The flush() function is used to empty the data stream in the buffer. During the stream operation, the data is first read into memory and then written to the file. When you finish reading the data, if we call the close() method to close the read-write stream, it may cause data loss. Why? Because the completion of reading data does not mean the completion of writing data, and some data may remain in the cache. At this time, the flush() method is particularly important.
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileWriter fw = new FileWriter("fw.txt");
        // Write out the data through flush
        fw.write('brush'); // Write the first character
        fw.flush();
        fw.write('new'); // Continue to write the second character and write successfully
        fw.flush();
      
      	// Write out the data through close
        fw.write('shut'); // Write the first character
        fw.close();
        fw.write('close'); // Continue to write the second character, [error] java.io.IOException: Stream closed
        fw.close();
    }
}

  • FileReader and FileWriter classes complete text file copying
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFile {
    public static void main(String[] args) throws IOException {
        //Create an input stream object
        FileReader fr=new FileReader("F:\\New folder\\aa.txt");//If the file does not exist, a java.io.FileNotFoundException will be thrown
        //Create output stream object
        FileWriter fw=new FileWriter("C:\\copyaa.txt");
        /*To create an output stream:
         *      1,A file is created by calling system resources
         *      2,Create output stream object
         *      3,Point the output stream object to the file        
         * */
        //Copy text files, one character at a time
        copyMethod1(fr, fw);
        //Copy the text file, reading one character array at a time
        copyMethod2(fr, fw);
        
        fr.close();
        fw.close();
    }

    public static void copyMethod1(FileReader fr, FileWriter fw) throws IOException {
        int ch;
        while((ch=fr.read())!=-1) {//Read data
            fw.write(ch);//Write data
        }
        fw.flush();
    }

    public static void copyMethod2(FileReader fr, FileWriter fw) throws IOException {
        char chs[]=new char[1024];
        int len=0;
        while((len=fr.read(chs))!=-1) {//Read data
            fw.write(chs,0,len);//Write data
        }
        fw.flush();
    }
}



6, Byte buffer stream

  • Construction method
    public BufferedInputStream(InputStream in): create a new buffered input stream. Note that the parameter type is InputStream.
    public BufferedOutputStream(OutputStream out): create a new buffered output stream. Note that the parameter type is OutputStream
//Construction method 1: create byte buffered input stream [but the following format declaration is commonly used in development]
FileInputStream fps = new FileInputStream(b.txt);
BufferedInputStream bis = new BufferedInputStream(fps)

//Construction method 1: create byte buffered input stream
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("b.txt"));

///Construction mode 2: create byte buffered output stream
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.txt"));

The essence of buffered stream is to speed up file transfer, especially for files with large memory.

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
      	// Record start time
        long start = System.currentTimeMillis();
		// Create flow object
        try (
		 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("py.exe"));
		 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copyPy.exe"));
        ){
          	// Read and write data
            int len;
            byte[] bytes = new byte[8*1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0 , len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// Record end time
        long end = System.currentTimeMillis();
        System.out.println("Buffer stream uses array copy time:"+(end - start)+" millisecond");
    }
}
Buffer stream uses array copy time:521 millisecond  // It is much faster than the basic transmission method

7, Character buffer stream

The basic method of character buffer stream is the same as that of ordinary character stream. It will not be described here. Let's look at the unique methods of character buffer stream.

BufferedReader: public String readLine(): read a line of data. null returned after reading
BufferedWriter: public void newLine(): line feed. Symbols are defined by system attributes.

public class BufferedWriterDemo throws IOException {
  public static void main(String[] args) throws IOException  {
    	// Create flow object
  	BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
    	// Write data
      bw.write("2222");
    	// Write line breaks
      bw.newLine();
     
  	// Release resources
      bw.close();
  }
}
Output effect:
2222
  • Comprehensive code
public class BufferedTest {
    public static void main(String[] args) throws IOException {
        // Create a map set and save text data. The key is sequence number and the value is text
        HashMap<String, String> lineMap = new HashMap<>();

        // Create stream object source
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        //target
        BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));

        // Read data
        String line  = null;
        while ((line = br.readLine())!=null) {
            // Parse text
            String[] split = line.split("\\."); //  \It's an escape character. Don't get it wrong. Just add a. To interval key and value
            // Save to collection
            lineMap.put(split[0],split[1]);//0 is the subscript of the key 
        }
        // Release resources
        br.close();

        // Traversal map set
        for (int i = 1; i <= lineMap.size(); i++) {
            String key = String.valueOf(i);
            // Get text in map
            String value = lineMap.get(key);
          	// Write the spliced text
            bw.write(key+"."+value);
          	// Write line breaks
            bw.newLine();
        }
		// Release resources
        bw.close();
    }
}

8, Conversion flow

  • InputStreamReader class ------ (bridge from byte stream to character stream)
  • Construction method
    InputStreamReader(InputStream in): creates a character stream that uses the default character set.
    InputStreamReader(InputStream in, String charsetName): creates a character stream with a specified character set.
  • The construction code is as follows:
InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));
InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");

Example

public class ReaderDemo2 {
    public static void main(String[] args) throws IOException {
      	// Define the file path. The file is gbk encoded
        String FileName = "C:\\A.txt";
      	// Create a stream object with the default UTF8 encoding
        InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));
      	// Create a stream object and specify the GBK encoding
        InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK");
		// Define variables and save characters
        int read;
      	// Use the default encoding character stream to read, garbled
        while ((read = isr.read()) != -1) {
            System.out.print((char)read); // �����ʺ      
        }
        isr.close();
      
      	// Read using the specified encoded character stream and parse normally
        while ((read = isr2.read()) != -1) {
            System.out.print((char)read);// I am a human
        }
        isr2.close();
    }
}
  • OutputStreamWriter class ------ (bridge from character stream to byte stream)
  • Construction method
    OutputStreamWriter(OutputStream in): creates a character stream that uses the default character set.
    OutputStreamWriter(OutputStream in, String charsetName): creates a character stream with a specified character set.
  • For example, the code is as follows:
OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("a.txt"));
OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("b.txt") , "GBK");

Example

public class OutputDemo {
    public static void main(String[] args) throws IOException {
      	// Define file path
        String FileName = "C:\\s.txt";
      	// Create a stream object with the default UTF8 encoding
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));
        // Write data
      	osw.write("I am a human"); 
        osw.close();
      	
		// Define file path
		String FileName2 = "D:\\A.txt";
     	// Create a stream object and specify the GBK encoding
        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");
        // Write data
      	osw2.write("I am a human");
        osw2.close();
    }
}

  • For maximum efficiency, consider wrapping InputStreamReader inside BufferedReader
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

Posted by rayk on Fri, 29 Oct 2021 19:26:12 -0700