Java byte stream

Catalog

Byte stream

  • byte stream class processes data in bytes;
  • The byte stream does not transform any data, so it can be used to process binary data;

1. input stream

  • The function of byte input stream is to get byte data from data input source (such as disk, network, etc.) to application (memory);
  • InputStream is an abstract class that defines the Java streaming byte input mode. All methods of this class will throw an IOException exception in case of an error;

a. Common methods of InputStream

type Method Explain
int available() Returns the number of input bytes currently readable
void close() Closing the input stream and reading it after closing will throw an IOException exception
void mark(int numBytes) Set a flag at the current point of the input stream that remains valid until numBytes are read
boolean markSupported() Returns true if the called stream supports mark()/reset()
int read() Returns an integer if the next byte is readable, - 1 when the end of the file is encountered
int read(byte buffer[]) Try to read buffer.length bytes to buffer, return the actual number of bytes read, and return - 1 when the end of the file is encountered
int read(byte buffer[], int offset, int numBytes) Try to read numBytes at the beginning of buffer[offset], return the number of bytes actually read, and return - 1 at the end of the file
void reset() Reset the input pointer to the previously set flag
long skip(long numBytes) Ignore numBytes input bytes, return the number of bytes actually ignored

b. FileInputStream class

Construction method Explain
FileInputStream(String filepath) The absolute path of the file, which is commonly used
FileInputStream(File fileObj) fileObj is the File object that describes the File, allowing you to further check the File with the File method before assigning the File to the input stream

c. Read and display files

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

public class Test {
    public static void main(String[] args) {
        byte[] b = new byte[1024];//Set byte buffer
        int n = -1;
        System.out.println("Please enter the file name to read:(For example: d:\\hello.txt)");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();//Get the file name to read

        try {
            FileInputStream in = new FileInputStream(str);//Create byte input stream
            while ((n = in.read(b, 0, 1024)) != -1) {//Read the contents of the file to the buffer and display
                String s = new String(b, 0, n);
                System.out.println(s);
            }
            in.close();//End of reading file, close file
        } catch (IOException e) {
            System.out.println("File read failed");
        }
    }
}
/*
output
 Please enter the file name to read: (for example: d:\hello.txt)
C:\Users\80626\Desktop\1.txt
ssssaaa Manual valve Aston
 */

2. output stream

  • The function of byte output stream is to transfer byte data from application program (memory) to output target, such as external device, network, etc;
  • OutputStream is an abstract class that defines Java stream byte output mode. All methods of this class will return a void value, and an IOException exception exception will be thrown in case of an error;

a. Common methods of OutputStream

type Method Explain
void close() Close the output stream, and an IOException will be thrown if you operate after closing
void flush() Flush output buffer
void write(int b) Write a single byte to the output stream, the parameter is an integer
void write(byte buffer[]) Write a complete byte array to an output stream
void write(byte buffer[], int offset, int numBytes) Write array buffer the contents of numBytes byte area starting from buffer[offset]

b. FileOutputStream class

Construction method Explain
FileOutputStream(String filepath) Absolute path to file
FileOutputStream(File fileObj) fileObj is the File object that describes the File
FileOutputStream(String filePath, boolean append) If append is true, the file is opened in set search path mode
  • The creation of FileOutputStream does not depend on the existence of the file. It will create the output file after it is opened. If you try to open a read-only file, an IOException exception will be thrown;
  • During the operation, the system will temporarily store the data in the buffer and write it to the output stream once the buffer is full. When the close() method is executed, the data in the buffer will be written to the output stream regardless of whether the buffer is full or not;

c. Write data

  • The second operation is completed by adding:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        String content;//String to be output
        byte[] b;//Output byte stream
        FileOutputStream out;//File output stream
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter a file name: (for example, d:\\hello.txt)");
        String filename = scanner.nextLine();
        File file = new File(filename);//Create a file object

        if (!file.exists()) {//Judge whether the file exists
            System.out.println("The file does not exist. Do you want to create it?(y/n)");
            String f = scanner.nextLine();
            if (f.equalsIgnoreCase("n"))
                System.exit(0);//Do not create, exit
            else {
                try {
                    file.createNewFile();//create a new file
                } catch (IOException e) {
                    System.out.println("Create failure");
                    System.exit(0);
                }
            }
        }

        try {//Write to file
            content = "Hello";
            b = content.getBytes();
            out = new FileOutputStream(file);//Create a file output stream
            out.write(b);//Write complete
            out.close();//Close output stream
            System.out.println("File write operation succeeded!");
        } catch (IOException e) {
            e.getMessage();
        }

        try {//Append content to file
            System.out.println("Please enter additional content:");
            content = scanner.nextLine();
            b = content.getBytes();
            out = new FileOutputStream(file, true);//Create an output stream of appendable content
            out.write(b);//Complete append write operation
            out.close();//Close output stream
            System.out.println("File append write operation succeeded!");
            scanner.close();
        } catch (IOException e) {
            e.getMessage();
        }
    }
}
/*
output
 Please enter a file name: (for example, d:\hello.txt)
C:\Users\80626\Desktop\1.txt
 File write operation succeeded!
Please enter additional content:
fsfad
 File append write operation succeeded!

file
Hellofsfad
 */

c. Write and read data

import java.io.*;

public class Test {
    public static void main(String args[]) {
        File f = new File("C:\\Users\\80626\\Desktop\\1.txt");
        OutputStream out = null;
        try {
            out = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // Convert string to byte array
        byte b[] = "Hello World!!!".getBytes();
        try {
            // Write byte array to file
            out.write(b);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            out.close();
        } catch (IOException e2) {
            e2.printStackTrace();
        }

        // Here are the read file operations
        InputStream in = null;
        try {
            in = new FileInputStream(f);
        } catch (FileNotFoundException e3) {
            e3.printStackTrace();
        }
        // Open up a space for receiving the data read in the file
        byte b1[] = new byte[1024];
        int i = 0;
        try {
            // Pass the reference of b1 to the read() method, and the method returns the number of read data
            i = in.read(b1);
        } catch (IOException e4) {
            e4.printStackTrace();
        }
        try {
            in.close();
        } catch (IOException e5) {
            e5.printStackTrace();
        }
        //Convert byte array to string output
        System.out.println(new String(b1, 0, i));
    }
}
/*
output
Hello World!!!

file
Hello World!!!
 */
211 original articles published, 213 praised, 8038 visited
Private letter follow

Tags: Java network

Posted on Wed, 11 Mar 2020 22:20:15 -0700 by IMP_TWI