IO Byte Stream (Java Foundation)

Keywords: Java jvm ascii Windows


There is nothing right or wrong in the world. Everything is just a measure of right or wrong!

Article Directory

Overview of IO

concept

In life, when you edit a text file and forget ctrl+s, the file may be edited in white.When you insert a U drive into your computer, you can copy a video to your computer hard disk.So what devices are the data on?Keyboard, memory, hard disk, external device, etc.
We can see this kind of data transmission as a flow of data, which is divided into input and output based on memory in the direction of flow, that is, flow to memory is input stream and output stream out of memory.

I/O operations in Java mainly refer to the use of content under the java.io package for input and output operations.Input is also called reading data, and output is also called writing out data.

The flow direction of the data is divided into input flow and output flow.

  • Input stream: A stream that reads data from other devices into memory.
  • Output stream: A stream that writes data from memory to other devices.
    The types of pattern data are divided into byte stream and character stream.
  • Byte stream: A stream that reads and writes data in bytes.
  • Character stream: A stream of data read and written in characters.

Diagram

Perhaps you'll be blurred by the underlying implementation, so let's first show the concept and classification diagram of IO streams

Byte Stream

Summary

About bytes:
All file data (text, pictures, videos, etc.) is stored as binary digits, one byte at a time, so it is the same when transmitted.Therefore, a byte stream can transfer any file data.When working with streams, it is always clear that no matter what stream object is used, the underlying transport is always binary data.

Any file can be read with knowledge of byte streams

Byte Output Stream


Method of Focus

Key information:
java.io.OutPutStream: This abstract class is a superclass of all classes representing the output byte stream.
Some member methods that are common to subclasses are defined:
public void close(): Close this output stream and release any system resources associated with it.
public void flush(): Refreshes this output stream and forces any buffered output bytes to be written out.
public void write(byte[] b): Writes b.length bytes from the specified byte array to this output stream.
public void write(byte[] b, int off, int len): Writes len bytes from the specified byte array, starting at offset off
Out to this output stream.
public abstract void write(int b): Outputs the specified byte stream.
Be careful:
The close method, which must be called to free system resources when the flow operation is complete.

As Abstract classes, we cannot use them directly.

ByteArrayOutputStream byte output stream
FileOutputStream File Byte Output Stream
FilterOutputStream Filter Byte Output Stream
ObjectOutputStream Object Output Stream
OutputStream This is a stream in another package
PipedOutputStream Pipeline Output Flow

FileOutputStream class


The java.io.FileOutputStream class is a file byte output stream used to write data out to a file.

Construction method:

A demonstration of the arrow
About parameters: Path to write data.
string name: Destination is the path to a file File file: Destination is the function of a file construction method:

  1. Create a FileOutputstream object
  2. An empty file is created based on the file/file path passed in the construction method
  3. The FileOutputStream object is referred to as the created file

How to write data (memory -> hard disk):
Java Programs --> JVM --> OS --> Methods for OS to Write Data --> Write Data to File

Steps to use the byte output stream (important):

  1. Create a FileOutputStream object that passes the destination of the written data in the construction method
  2. Call the method write in the FileOutputStream object to write data to a file
  3. Release resources (Stream usage takes up a certain amount of memory, empty memory after use, provider efficiency)
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        //1. Create a FLLeoutputstream object and pass the destination of the written data in the construction method
        FileOutputStream fos = new FileOutputStream("C:\\Users\\JunQiao Lv\\Desktop\\file\\b.txt");
        //2. Call the method write in the FileOutputstream object to write data to a file
        fos.write(97);
        //3. Release resources (Stream consumes a certain amount of memory, empty memory after use, provider efficiency)
        fos.close();
    }
}

Result:

Open the file:

Byte Input Bleeding Multiple Bytes Method:
This is a write-once scenario

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        //Create a FileOutputStream object and bind the destination to write data to in the construction method
        FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\JunQiao Lv\\Desktop\\file\\a.txt"));
        //Call the method write in the FileOutputStream object to write data to a file
        //Show 100 in file, write 3 bytes
        fos.write(49);
        fos.write(48);
        fos.write(48);
        //Release Resources
        fos.close();
    }
}

Result:


This is multiple times:
public void write (byte[] b): Writes b.length bytes from the specified byte array to this output stream.
Write more than one byte at a time:
If the first byte written is a positive number (0 - 127), the ASCII table is queried when displayed
If the first byte written is a negative number, then the first byte and the second byte, which form a Chinese display, query the system default code table (GBK)
UTF-8 Three bytes is one Chinese

public void write (byte[] b, int off, int len): Writes a part of the byte array to a file
Beginning index of off array
len writes a few bytes

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws IOException {
        //Create a FileOutputStream object and bind the destination to write data to in the construction method
        FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\JunQiao Lv\\Desktop\\file\\b.txt"));
        //Call the method write in the FileOutputStream object to write data to a file
        //Show 100 in file, write 3 bytes
        fos.write(49);
        fos.write(48);
        fos.write(48);
        byte[] bts = {65,66,67,68,69};
        fos.write(bts);
        fos.write(bts,0,3);
        //Extension: Link to the String class reviewed earlier
        byte[] bts3 = "Hello".getBytes();
        System.out.println(Arrays.toString(bts3));
        fos.write(bts3);
        //Release Resources
        fos.close();
    }
}

Result:

FileOutputStream(String name, boolean append)
Creates a file output stream to write to the file with the specified name.
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

Parameters:
String name,File file: Destination to write data
boolean append: append write switch
* true: Create object will not overwrite the source file, continue appending data to the end of the file
* false: Create a new file to overwrite the source file

Write Wrap: Write Wrap Symbol
windows:Irin
Linux:/n
mac:/r

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("C:\\Users\\JunQiao Lv\\Desktop\\file\\c.txt",true);
        for (int i = 0; i < 10; i++) {
            fos.write("How do you do".getBytes());
            fos.write("\r\n".getBytes());
        }
        fos.close();
    }
}

Result:

Byte Input Stream


This is also an abstract class
Method:

java.io.InputStream: Byte input stream This abstract class is a superclass of all classes representing byte input streams.
A method that defines the commonality of all subclasses is defined:
int read() reads the next byte of data from the input stream.
int read (byte[]b) reads a certain number of bytes from the input stream and stores them in the buffer array B.
void close() closes this input stream and releases all system resources associated with it.

Focus on implementation classes

FileInputStream: File byte input stream
Role: Read data from hard disk files into memory for use
Construction method:

Parameter: Data source to read file
String name: Path to file
File file:

Role of construction methods:

  1. A FileInputStream object is created
  2. The FileInputStream object is specified as the file to be read in the construction method\

Byte Input Stream Reads Byte Data

Single read:
How to read data (hard disk - > memory)
java program ->JVM ->OS ->How the OS reads data ->Read files

Steps to use byte input stream

  1. Create a FileInputStream object and bind the data source to read in the construction method
  2. Read the file using the method read in the FileInputStream object
  3. Release Resources

Test: content in a.txt is abc

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

public class Main {
    public static void main(String[] args) throws IOException {
        //1. Create a FileInputStream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("C:\\Users\\JunQiao Lv\\Desktop\\file\\a.txt");
        //2. Read the file using the method read in the FileInputStream object
        //int read() reads a byte in the file and returns it, and returns -1 when read to the end of the file
        int len = fis.read();
        System.out.println(len);
        len = fis.read();
        System.out.println(len);
        len = fis.read();
        System.out.println(len);
        len = fis.read();
        System.out.println(len);
        //Simplified Writing
//        while((len= fis.read())!= -1 ){
//            System.out.println(len);
//            System.out.println((char)len);
//        }
        //3. Release resources
        fis.close();
    }
}

Result:

Multiple Reads
Byte input stream read multiple bytes at once:
int read (byte[]b) reads a certain number of bytes from the input stream and stores them in the buffer array B.
There is a confounding point
read() has a parameter that returns the number of bytes read
Returns the character encoding value for that byte without parameters

Make two things clear:
1. The function of the parameter byte[J] of the method?
Buffers, storing multiple byte arrays read at a time, one integer multiple of 1024 (1kb) or 1024
2. What is the return value int of the method?
Number of valid bytes per read

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws IOException {
        ///Create FileInputStream object, bind data source to read in construction method
        FileInputStream fis = new FileInputStream("C:\\Users\\JunQiao Lv\\Desktop\\file\\d.txt");
        //Use the method read file in the FileInputStream object
        //int read(byte[] b) reads a certain number of bytes from the input stream and stores them in the buffer array B.
        byte[] bytes = new byte[3];
        int len = fis.read(bytes);
        System.out.println(len);
        System.out.println(Arrays.toString(bytes));
        System.out.println(new String(bytes));
        //Release Resources
        fis.close();
    }
}

Result:

Optimize:

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

public class Main {
    public static void main(String[] args) throws IOException {
        ///Create FileInputStream object, bind data source to read in construction method
        FileInputStream fis = new FileInputStream("C:\\Users\\JunQiao Lv\\Desktop\\file\\d.txt");
        //Use the method read file in the FileInputStream object
        //int read(byte[] b) reads a certain number of bytes from the input stream and stores them in the buffer array B.
        byte[] bytes = new byte[1024];  //
        int len = 0; //Record the number of valid bytes per read
        while ( (len = fis.read(bytes)) != -1){
            System.out.println(new String(bytes,0,len));
        }
        //Release Resources
        fis.close();
    }
}

Result:

File Copy:
The principle of file copying:

If code is to be involved:

Demonstrate it once:
Copy d.txt of C:\Users\JunQiao Lv\Desktop\file to C:\Users\JunQiao Lv\Desktop\file\hehe

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {

        FileInputStream fis = new FileInputStream("C:\\Users\\JunQiao Lv\\Desktop\\file\\d.txt");
        FileOutputStream fos = new FileOutputStream("C:\\Users\\JunQiao Lv\\Desktop\\file\\hehe\\d.txt");
        int len = 0;
//        while ((len = fis.read())!=-1){
//            fos.write(len);
//        }
        //optimization
        byte[] bytes = new byte[1024];
        while ((len = fis.read(bytes)) != -1){
            fos.write(bytes,0,len);
        }
        fos.close();
        fis.close();
    }
}

Testing is normal.

Use Byte Stream to Read Chinese Problems

Using Byte Stream to Read Chinese Files
1 Chinese
GBK: Two bytes
UTF-8: takes up 3 bytes

So there may be a minor problem when reading text files using byte streams.That is, when Chinese characters are encountered, the complete characters may not be displayed, because
A Chinese character may take up more than one byte of storage.So Java provides some character stream classes that read and write data in character units, designed to work with text
Parts.

To avoid getting too long and bloated, start another article here.

Posted by powlouk on Thu, 09 May 2019 19:10:40 -0700