This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging

IO stream overview and classification

IO flow is introduced

  • I /O: Input/Output
  • Stream: an abstract term for data transfer. In other words, the transmission of data between devices is called stream, and the essence of stream is data transmission
  • IO streams are used to deal with data transfer between devices. Common applications: file replication; File upload; File download

Classification of I/O streams

  • According to the flow of data
    • Input stream: read data
    • Output stream: write data
  • By data type
    • Byte stream
      • Byte input stream
      • Byte output stream
    • Characters of the flow
      • Character input stream
      • Character output stream

Usage scenarios for I/O streams

  • If you are working with a plain text file, the character stream is preferred
  • If you operate binary files such as pictures, videos, and audio files. Byte streams are preferred
  • If the file type is uncertain, the byte stream is preferred. A byte stream is a versatile stream

Byte stream write data

Byte stream abstract base class

  • InputStream: This abstract class is the superclass of all classes that represent byte input streams
  • OutputStream: This abstract class is a superclass of all classes that represent byte output streams
  • Characteristics of subclass names: The subclass name is the suffix of the name of its parent class

Byte output stream

  • FileOutputStream(String name) : creates a FileOutputStream and writes it to the file with the specified name

Steps to write data using a byte output stream

  • Create byte output stream object (call system function to create file, create byte output stream object, make byte output stream object point to file)
  • Calls the write data method of the byte output stream object
  • Resource release (closes the file output stream and frees any system resources associated with the stream)
public class FileOutputStreamLearn {
  public static void main(String[] args) throws  IOException {
      // Create a byte output stream object
      //FileOutputStream(String name) : creates a FileOutputStream and writes it to the file with the specified name
      FileOutputStream fos = new FileOutputStream("File\HelloWord.txt");
        /* Do three things: A: call the system function to create the file B: create the byte output stream object C: make the byte output stream object point to the created file */

      // Writes the specified bytes to the file output stream
      fos.write(97);/ / character a
      fos.write(57);/ / 9 characters
      fos.write(55);/ / 7 characters

      // Finally, you have to release resources
      // Close the file output stream and release any system resources associated with the stream.fos.close(); }}Copy the code

Three ways for byte streams to write data

Classification of methods for writing data

The method name instructions
void write(int b) Writes the specified byte to the file output stream, one byte at a time
void write(byte[] b) Writes the B. length byte from the specified byte array to the file output stream, one byte array data at a time
void write(byte[] b, int off, int len) Writes len bytes from the specified byte array, starting at the offset off, to the file output stream one byte at a time
public FileOutputStream(String name) throws FileNotFoundException {
    this(name ! =null ? new File(name) : null.false);
}
Copy the code

So the two approaches are essentially the same

FileOutputStream fos = new FileOutputStream("File\HelloWord.txt"); Equivalent to FileOutputStream fos =new FileOutputStream(new File("File\HelloWord.txt"));
Copy the code
public class FileOutputStreamLearn {
   public static void main(String[] args) throws IOException {
       //FileOutputStream(String name) : creates a FileOutputStream and writes it to the file with the specified name
       //FileOutputStream fos = new FileOutputStream("File\HelloWord.txt"); == FileOutputStream fos = new FileOutputStream(new File("File\HelloWord.txt"));
       FileOutputStream fos = new FileOutputStream("File\HelloWord.txt");

       //FileOutputStream(File File) : Creates a File output stream to write to the File represented by the specified File object
               File file = new File("File\HelloWord.txt");
               FileOutputStream fos2 = new FileOutputStream(file);
               FileOutputStream fos3 = new FileOutputStream(new File("File\HelloWord.txt"));

       //void write(int b) : writes the specified byte to the file output stream
               fos.write(97);
               fos.write(98);
               fos.write(99);
               fos.write(100);
               fos.write(101);

       //void write(byte[] b) : writes the B. length byte from the specified byte array to the file output stream
       //byte[] bys = {97, 98, 99, 100, 101};
       //byte[] getBytes() : returns the byte array corresponding to the string
       byte[] bys = "abcde".getBytes();
               fos.write(bys);

       //void write(byte[] b, int off, int len) : write len bytes from the specified byte array to the output stream
       // fos.write(bys,0,bys.length);
       fos.write(bys,1.3);

       // Release resourcesfos.close(); }}Copy the code

Two small problems with byte Stream writing

How to wrap byte stream write data

  • windows:\r\n
  • linux:\n
  • mac:\r

How to append to byte stream write data

  • public FileOutputStream(String name,boolean append)
  • Creates a file output stream that writes to the file with the specified name. If the second argument is true, bytes are written to the end of the file instead of the beginning
public class FileOutputStreamLearn2 {
  public static void main(String[] args) throws IOException {
      // Create a byte output stream object
      // FileOutputStream fos = new FileOutputStream("myByteStream\fos.txt");
      FileOutputStream fos = new FileOutputStream("File\HelloWord2.txt".true);

      / / write data
      for (int i = 0; i < 10; i++) {
          fos.write("hello".getBytes());
          fos.write("\r\n".getBytes());
      }

      // Release resourcesfos.close(); }}Copy the code

Of course, we usually use a try-catch-finally method for items. It is not recommended to throw an exception directly

public class FileOutputStreamLearn2 {
    public static void main(String[] args)  {
        // Create a byte output stream object
        //FileOutputStream fos = new FileOutputStream("myByteStream\fos.txt");
        FileOutputStream fos = null;
        //--------------
        try {
            fos = new FileOutputStream("File\HelloWord2.txt".true);
            / / write data
            for (int i = 0; i < 10; i++) {
                fos.write(("hello word" + i).getBytes());
                fos.write("\r\n".getBytes()); }}catch (IOException e) {
            // This is where exceptions are handled
            e.printStackTrace();
        } finally {
            // Release resources
            try {
                fos.close();
            } catch(IOException e) { e.printStackTrace(); }}//--------------}}Copy the code

Byte stream reads data

Byte input stream

  • FileInputStream(String Name) : Creates a FileInputStream by opening a connection to the actual file, which is named by the file system pathname name

Byte input stream to read the data step

  • Creates a byte input stream object
  • Calls the read data method of the byte input stream object
  • Release resources
public class FileOutputStreamLearn3 {
  public static void main(String[] args) throws IOException {
      // Create a byte input stream object
      //FileInputStream(String name)
      FileInputStream fis = new FileInputStream("File\HelloWord2.txt");

      int by;
        /* fis.read() : read data by=fis.read() : assign the read data to by by! = -1: checks whether the read data is -1 */
      while((by=fis.read())! = -1) {
          System.out.print((char)by);
      }

      // Release resourcesfis.close(); }}Copy the code