Java IO byte stream

summary

What is IO?

IO is what I / O stream means. Based on memory, it can be divided into input and output, that is to say, the flow to memory is the input flow and the output flow out of memory.

  • Input stream: read data from hard disk to memory for use
  • Output stream: write data in memory to hard disk for saving

The table above is the top-level parent class

Byte stream

Everything is byte

All file data (text, picture, video, etc.) are stored in the form of binary numbers, one byte at a time, so it is the same when transferring.

Therefore, a byte stream can transfer arbitrary file data. When operating the flow, we should always be clear that no matter what kind of flow object is used, the underlying transmission is always binary data.

Byte input stream

java.io.InputStream ``Abstract class is a super class representing all classes of byte input stream, which can read byte information into memory.

It defines the basic common function method of byte input stream.

  • public abstract int read(): reads the next byte of data from the input stream.
  • public int read(byte[] b): read some bytes from the input stream and store them in byte array B.
  • public void close(): closes the input stream and releases any system resources associated with the stream.

FileInputStream

java.io.FileInputStream Class is a file input stream that inherits the InputStream abstract class. publicclass FileInputStream extends InputStream

The function is to read the data in the hard disk file and use it in memory.

Principle of reading data (hard disk - > memory): Java program -- > JVM -- > operating system -- > call local method -- > read file content

Construction method
Constructor Description
FileInputStream(File file) * Create a FileInputStream by opening a connection to the actual File named after the File object File in the File system.
FileInputStream(String name) Create a FileInputStream by opening a connection to the actual file named by the pathname in the file system.
FileInputStream(FileDescriptor fdObj) Creating a FileInputStream uses the file descriptor fdObj, which represents an existing connection in the file system to an actual file.

When you create a stream object, you must pass in a file path. If there is no such file in this path, FileNotFoundException will be thrown.

common method
method describe
int read() Read a data byte from this input stream.
int read(byte[] b) Read up to b.length bytes of data into a byte array from this input stream.
int read(byte[] b, int off, int len) Read up to len bytes of data into a byte array from this input stream.
void close() Close this file input stream and free all system resources associated with this stream.
long skip(long n) Skips and discards n bytes of data from the input stream.
protected void finalize() Make sure to call the file input stream's close method when it is no longer referenced.
int available() Returns the estimated number of bytes remaining that the next method called on this input stream can read (or skip) from this input stream without blocking.
FileChannel getChannel() Returns the unique FileChannel object associated with this file input stream.
FileDescriptor getFD() Returns a FileDescriptor object that represents a connection to the actual file in the file system that is being used by this FileInputStream.

*In the file byte input stream, the read() bottom layer calls the local method read0()

The other two read methods call the local method readBytes(byte b[], int off, int len)


Use steps
  1. Create FileInputStream object and bind data source in construction method
  2. Use the read method in the FileInputStream object to read the data
  3. Release resources
package IO;

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

public class FileInputStream_in {
	public static void main(String args[]) throws IOException{
		
		//read("1.txt");
		//readMore("1.txt");
		readAll("1.txt");
	}
	public static void read(String path) throws IOException{
		FileInputStream fis = new FileInputStream(path);
		int len =0;
		while((len = fis.read())!=-1)
			System.out.print((char)len);
		
		fis.close();
		
	}
	
	public static void readMore(String path) throws IOException{
		FileInputStream fis = new FileInputStream(path);
		int len =0;
		byte[] bytes = new byte[2];
		while((len = fis.read(bytes))!=-1)
			System.out.println(new String(bytes));
		
		fis.close();
		
	}
	//Optimize previous method
	public static void readAll(String path) throws IOException{
		FileInputStream fis = new FileInputStream(path);
		int len =0;
		byte[] bytes = new byte[1024];
		while((len = fis.read(bytes))!=-1)
			System.out.print(new String(bytes,0,len));//Take only the effective part
		
		fis.close();
		
	}
}

Byte output stream

java.io.OutputStream Abstract class is a super class representing all classes of byte output stream, writing out the specified byte information to the destination.

It defines the basic common function method of byte output stream.

  • public void close(): closes the output stream and releases any system resources associated with the stream.
  • public void flush(): flushes the 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, and outputs to the output stream from the offset off.
  • public abstract void write(int b): outputs the specified byte stream.

method describe
void close() Close this output stream and release all system resources associated with it.
void flush() Flushes this output stream and forces all buffered output bytes to be written out.
void write(byte[] b) Writes b.length bytes from the specified byte array to this output stream.
void write(byte[] b, int off, int len) Writes len bytes from the offset off in the specified byte array to this output stream.
abstract void write(int b) Writes the specified bytes to this output stream.

*In the byte output stream, the write(int b) method is called by the write overloaded method

File byte output stream

java.io.FileInputStream Class is the file input stream that reads bytes from the file.

Principle of writing data (memory - > hard disk): Java program -- > JVM -- > operating system -- > calls local method -- > writes data to file

Construction method
  • FileInputStream(File file): creates a FileInputStream by opening a connection to the actual file named by the file object file in the file system.
  • FileInputStream(String name): creates a FileInputStream by opening a connection to the actual file named by the pathname in the file system.

When you create a stream object, you must pass in a file path. If there is no such file in this path, FileNotFoundException will be thrown.

Constructor Description
FileOutputStream(File file, boolean append) ** Creates a File output stream to write to the File represented by the specified File object.
FileOutputStream(String name, boolean append) Creates a file output stream to write to the file with the specified name. Append is the append switch. The default is false.
FileOutputStream(String name) Creates a file output stream to write to the file with the specified name.
FileOutputStream(File file) Creates a File output stream to write to the File represented by the specified File object.
FileOutputStream(FileDescriptor fdObj) * Creates a file output stream to write to the specified file descriptor, representing an existing connection to the actual file in the file system.

In fact, no matter which constructor is converted to the form of fileoutputstream (file, Boolean append)

common method
method describe
Void write (int b) * * core Writes the specified bytes to this file output stream.
void write(byte[] b) Writes b.length bytes from the specified byte array to the output stream of this file.
void write(byte[] b, int off, int len) Writes len bytes in the specified byte array starting from offset off to the output stream of this file.
void close() Close this file output stream and free all system resources associated with this stream.
protected void finalize() Clean up the connection to the file and ensure that the close method of the file output stream is called when it is no longer referenced.
FileChannel getChannel() Returns the unique FileChannel object associated with this file output stream.
FileDescriptor getFD() Returns the file descriptor associated with this stream.

The underlying layer calls the native methods write(int b, boolean append) and writeBytes(byte b[], int off, int len, boolean append)

In the file byte output stream, the write overload method calls different local methods.

example
//Write a byte to the file with the output of file byte
import java.io.*;
public class fileIO {

		public static void main(String args[]) throws IOException{
			FileOutputStream fos = new FileOutputStream("1.txt");
			fos.write(97);//Enter a binary 1100001 of byte 97
			fos.close();//Open Notepad. The ASCII table corresponding to the default read character 97 is a
		}
}

package IO;
import java.io.*;
import java.util.Arrays;


public class FileOutputStream_ {

		public static void main(String args[]) throws IOException{
			fileOutOne("1.txt",97);//Write 1 byte (8 bits) 0110001 to 1 file
			
			byte[] t = "Hello".getBytes();
			System.out.println(Arrays.toString(t)); //gdk takes two bytes in both Chinese and English. utf-8 one byte in English and three bytes in Chinese
			fileOutMore("2.txt",t);//Write the byte array of Hello string conversion to 2 file.
			
			byte[] b = {97,98,49,48,48};
			fileOutMore1("3.txt",b);//Write a specified byte array to the 3 file.
			
		}
		
		//Write a byte to a file using byte output
		public static void fileOutOne(String path,int num) throws IOException{
			FileOutputStream fos = new FileOutputStream(path);//File to path
			fos.write(num);//Enter a binary 1100001 of byte 97
			fos.close();//Open Notepad. The ASCII table corresponding to the default read character 97 is a
		}
		
		//Write multiple bytes to a file using byte output
		public static void fileOutMore(String path,byte[] bytes) throws IOException{
			File f = new File(path);
			FileOutputStream fos = new FileOutputStream(f);//Point to specific documents
			
			fos.write(bytes);//Write a byte array
		
			fos.close();
		}
		
		//Use byte output to write multiple bytes of offset to file
		public static void fileOutMore1(String path,byte[] bytes) throws IOException{
			File f = new File(path);
			FileOutputStream fos = new FileOutputStream(f);//Point to specific documents
			
			//byte[] b = {97,98,49,48,48}; it should be ab100, offset two bits, write three bits and get 100
			fos.write(bytes,2,3);//Enter an array of bytes
		
			fos.close();
		}
}

Append and wrap
package IO;

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

public class FileOutputStrean_append {

	public static void main(String args[]) throws IOException{
		fileOutAppend("1.txt","append".getBytes());//Append line breaks and write a word to the 1 file
	}
	
	public static void fileOutAppend(String path,byte[] bytes) throws IOException{
		FileOutputStream fos = new FileOutputStream(path,true);//true flag append
		
		fos.write("\r\n".getBytes());//Line breaking symbols of files in Windows system
		
		fos.write(bytes);//Write a byte array
	
		fos.close();
	}
}

Copy file

step

  1. Create a byte input stream object and bind the data source to be read in the construction method
  2. Create a byte output stream object and bind the destination to be written in the construction method
  3. Use the read method of byte input stream object to read data
  4. Write the read data to the destination file using the write method of the direct output stream object
  5. Release resources (stack order, first in first out)
package bytestream;

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

public class CopyFile {
    public static void main(String[] args) throws IOException {
        // 1. Create a byte input stream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("test.txt");
        // 2. Create a byte output stream object and bind the destination to be written in the construction method
        FileOutputStream fos = new FileOutputStream("test2.txt");
        // 3. Use read method of byte input stream object to read data
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fis.read(bytes)) != -1) {

            // 4. Write the read data to the destination file using the write method of the direct output stream object
            fos.write(bytes, 0, len);
        }
        // 5. Release resources (stack order, first in first out)
        fos.close();
        fis.close();
    }
}

problem

Encoding of Chinese characters

  • GBK in two bytes
  • UTF-8 takes up three bytes
package bytestream;

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

public class ByteStreamTest {
    public static void main(String[] args) throws IOException {
        // There are some problems when using a byte stream to read characters
        FileInputStream fis = new FileInputStream("test.txt");

        int len = 0;
        while ((len = fis.read()) != -1) {
            System.out.println((char)len);
        }
        fis.close();
    }
}

test.txt

123789456 hello

Operation results

1
2
3
7
8
9
4
5
6
ä
½
 
å
¥
½

Using byte stream to read character data appears garbled code!

Problems with byte streams: when using byte streams to read text files, there may be a small problem. When Chinese characters are encountered, the complete characters may not be displayed,

That's because a Chinese character may occupy more than one byte. So Java provides some character stream classes to read and write data in character units, which are specially used for processing text files.

Tags: Java jvm ascii Windows

Posted on Sun, 31 May 2020 04:50:49 -0700 by Possum