The input and output here are relative to our Java code, the byte input stream, which is read into our program, and the byte output stream which is written into our file

Byte input stream

InputStream: this abstract class is a superclass of all classes that represent the InputStream, and this is part of its method

FileInputStream: is a subclass of InputStream. It is constructed as follows

Here is an example of a file that reads A.txt. In this file, I write hello world, so if I don’t write n below, there will be a bug

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

public class Main {
    public static void main(String[] args) {
        try {
            InputStream in = new FileInputStream("C:\\Users\\Administrator\\Desktop\\a.txt");
            byte[] bytes = new byte[2]; // I write 2 here for demonstration purposes, usually write 1024
            int n;
            while((n = in.read(bytes)) ! = -1) {
                String s = new String(bytes,0,n);// This cannot be written as bytes directly, otherwise it may be read incorrectly
                System.out.println(s);
            }
            in.close();
        } catch(IOException e) { e.printStackTrace(); }}}Copy the code

Running results:

Byte output stream

OutputStream: this abstract class is a superclass of all classes that represent a byte OutputStream. Here are its methods

FileOutputStream: a subclass of OutputStream. It is constructed as follows

This shows how to read a.txt files and write to b.txt files

import java.io.*;

public class Main {
    public static void main(String[] args) {
        try {
            InputStream in = new FileInputStream("C:\\Users\\Administrator\\Desktop\\a.txt");
            OutputStream os = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\b.txt");
            byte[] bytes = new byte[2];
            int n;
            while((n = in.read(bytes)) ! = -1) {
                os.write(bytes,0,n); // The same thing happens when you don't write n
            }
            in.close();
            os.close();
        } catch(IOException e) { e.printStackTrace(); }}}Copy the code