1, Buffer stream
Buffer stream is also called efficient stream, which is an enhancement of four basic FileXxx streams. Therefore, it is also four streams, which are divided into:
Byte buffer stream: BufferedInputStream,BufferedOutputStream Character buffer stream: BufferedReader,BufferedWriter
Basic principle of buffer flow:
When creating a stream object, a built-in buffer array of default size will be created to reduce the number of system IO through buffer reading and writing, so as to improve the efficiency of reading and writing.
1.1 byte buffered output stream
java.io.BufferedOutputStream extends OutputStream BufferedOutputStream:Byte buffered output stream
Common member methods inherited from parent class:
public void close():Close this output stream and free any system resources associated with this stream public void flush():Refresh this output stream and force any buffered output bytes to be written out. public void write(byte[] b):take b.length Bytes writes to this output stream from the specified byte array public void write(byte[] b, int off, int len):Writes from the specified byte array len Byte, offset from off Start output to this output stream public abstract void write(int b):Outputs the specified bytes to the stream
Construction method:
BufferedOutputStream(OutputStream out) Create a new buffered output stream to write data to the specified underlying output stream BufferedOutputStream(OutputStream out, int size) Creates a new buffered output stream to write data with the specified buffer size to the specified underlying output stream Parameters: OutputStream out: Byte output stream Can pass FileOutputStream,The buffer stream will give FileOutputStream Add a buffer to improve FileOutputStream Write efficiency int size: Specifies the size of the internal buffer of the buffer stream. If it is not specified, it will default
Use steps (key points):
1.Create a FileOutputStream Object to bind the destination to be output in the construction method 2.establish BufferedOutputStream Object, passed in construction method FileOutputStream Object, improve FileOutputStream Object efficiency 3.use BufferedOutputStream Methods in objects write,Write data to internal buffer 4.use BufferedOutputStream Methods in objects flush,Flush the data in the internal buffer into the file 5.Release resources (will be called first) flush Method to refresh data, step 4 can be omitted)
1.2 byte buffered input stream
java.io.BufferedInputStream extends InputStream BufferedInputStream:Byte buffered input stream
Member methods inherited from parent class:
int read() Read the next byte of data from the input stream, [read one byte at a time] int read(byte[] b) Read a certain number of bytes from the input stream and store them in the buffer array b in void close() Close this input stream and release all system resources associated with it
Construction method:
BufferedInputStream(InputStream in) Create a BufferedInputStream And save its parameters, that is, the input stream in,For future use BufferedInputStream(InputStream in, int size) Creates a with the specified buffer size BufferedInputStream,And save its parameters, that is, the input stream in,For future use. Parameters: InputStream in: Byte input stream Can pass FileInputStream,The buffer stream will give FileInputStream Add a buffer to improve FileInputStream Read efficiency int size:Specifies the size of the internal buffer of the buffer stream without specifying the default
Use steps (key points):
1.Create a FileInputStream Object to bind the data source to be read in the construction method 2.Create a BufferedInputStream Object, passed in construction method FileInputStream Object, improve FileInputStream Object reading efficiency 3.use BufferedInputStream Methods in objects read,read file 4.Release resources
1.3 character buffer output stream
java.io.BufferedWriter extends Writer BufferedWriter:Character buffered output stream
Common member methods inherited from parent class:
void write(int c) Write a single character void write(char[] cbuf) Write character array void write(char[] cbuf, int off, int len) Write part of the character array, off The start index of the array, len Number of characters written void write(String str) Write string void write(String str, int off, int len) Write a part of a string, off The start index of the string, len Number of characters written void flush() Flush the buffer of the stream void close() Close this stream, but refresh it first
Construction method:
BufferedWriter(Writer out) Create a buffered character output stream that uses the default size output buffer BufferedWriter(Writer out, int size) Creates a new buffered character output stream using an output buffer of a given size Parameters: Writer out: Character output stream Can pass FileWriter,Will give FileWriter Add a buffer to improve FileWriter Write efficiency int size:Specifies the size of the internal buffer of the character buffered output stream, not the default size
Unique member methods:
void newLine() Write a line separator. Different line separators will be obtained according to different operating systems Line breaks: line break symbols Windows: \r\n Linux:/n Mac: /r
Use steps:
1.Create a character buffer output stream object and pass the character output stream in the construction method 2.Method of calling character buffered output stream write,Write data to memory buffer 3.Method of calling character buffered output stream flush,Flush the data in the memory buffer into the file 4.Release resources
Knowledge expansion:
System.out.println()In fact, it is called newLine()Method realizes line feed operation Source code: public void println() { newLine(); }
1.4 character buffer input stream
java.io.BufferedReader extends Reader BufferedReader:Character buffered input stream
Common member methods inherited from parent class:
int read() Read a single character and return. int read(char[] cbuf) Read multiple characters at a time and read the characters into the array void close() Close the flow and release all resources associated with it
Construction method:
BufferedReader(Reader in) Create a buffered character amount stream using the default size input buffer BufferedReader(Reader in, int size) Creates a buffered character input stream using an input buffer of the specified size Parameters: Reader in: Character input stream Can pass FIleReader,The buffer stream will give FileReader Add a buffer to improve FileReader Read efficiency int size:Specifies the size of the input buffer
Unique member methods:
String readLine() Read a text line, that is, read a line of data Line termination symbol: a line can be considered terminated by one of the following characters: line feed('\n'),enter('\r')Or enter and follow the line feed directly(\r\n) Return value: The string containing the contents of this line does not contain any terminator. If it has reached the end of the stream, it returns null,no-1
Use steps:
1.Create a character buffered input stream object and pass the character input stream object in the construction method 2.Method of buffering input stream with characters read perhaps readLine Read text 3.Release resources
2, Conversion flow
Character encoding and character set:
Code: characters (understandable)-->Byte (unreadable) Decoding: bytes (not understood)-->Characters (readable)
Character Encoding: it is a set of correspondence rules between natural language characters and binary numbers
Coding table: the corresponding rules between words in life and binary in computer
Charset: also known as code table, it is a set of all characters supported by the system, including national characters, punctuation marks, graphic symbols, numbers, etc.
Common character sets include: ASCII character set, GBK character set, Unicode character set, etc.
A set of characters must have at least one set of character codes.
ASCII Character set: ASCII code GBK Character set: GBK code Unicode Character set: UTF8 Coding UTF16 Coding UTF32 code be careful: GBK Two bytes in represent a Chinese, UTF8 Three bytes in the represent a Chinese character.
It can be seen that when the encoding is specified, its corresponding character set is specified naturally, so the encoding is what we should care about ultimately.
2.1 FileWriter & FileReader
FileReader can read files in IDE default encoding format (UTF-8)
When FileReader reads the system default encoding format (GBK), it will generate garbled code
FileReader can only use IDE default encoding table (UTF-8)
Source code analysis:
public FileReader(String fileName) throws FileNotFoundException { super(new FileInputStream(fileName)); }
It can be seen that the bottom layer of FileReader also reads bytes through [byte input stream], and then converts bytes into characters through FileReader (FileReader queries UTF-8 code table, and converting bytes into characters is the decoding process).
2.2 how to read GBk encoded files?
Use the transform stream InputStreamReader:
[InputStreamReader It is a bridge from byte flow to character flow, which can be queried IDE Default code table( UTF-8),You can also query the specified code table.
Similarly, for FileWriter, only the IDE default code table (UTF-8) can be used to write the data in memory to the hard disk.
We can use the transform stream OutputStreamWriter to specify the encoding format. [OutputStreamWriter is a bridge between character flow and byte flow].
Source code analysis:
public class FileWriter extends OutputStreamWriter { public FileWriter(String fileName) throws IOException { super(new FileOutputStream(fileName)); } }
It can be seen that the bottom layer of FileWriter is to convert characters into bytes through byte output stream (that is, the process of encoding)
2.3 conversion flow action
The conversion stream can specify an encoding table.
2.4 java.io.OutputStreamWriter extends Writer
Buffered stream OutputStreamWriter: it is a bridge between character stream and byte stream: the characters to be written to the stream can be encoded into bytes using the specified charset.
Common member methods inherited from parent class:
void write(int c) Write a single character void write(char[] cbuf) Write character array void write(char[] cbuf, int off, int len) Write part of the character array, off The start index of the array, len Number of characters written void write(String str) Write string void write(String str, int off, int len) Write a part of a string, off The start index of the string, len Number of characters written void flush() Flush the buffer of the stream void close() Close this stream, but refresh it first
Construction method:
OutputStreamWriter(OutputStream out) Create a with default character encoding OutputStreamWriter OutputStreamWriter(OutputStream out, String CharsetName) Creates a with the specified character set OutputStreamWriter Parameters: OutputStream out:Byte output stream, which can be used to write converted bytes to the file String CharsetName: The specified encoding table name is not case sensitive and is used by default UTF-8
Use steps:
1.Create a OutputStreamWriter Object that passes the byte output stream and the specified encoding table name in the construction method 2.use OutputStreamWriter Methods in objects writer,Convert characters into bytes and store them in the buffer (i.e. the process of encoding) 3.use OutputStreamWriter Methods in objects flush,Flush the bytes in the memory buffer into the file (the process of writing bytes using the byte output stream) 4.Release resources
2.5 java.io.InputStreamReader extends Reader
Buffer stream InputStreamReader: it is a bridge between byte flow and character stream: it uses the specified charset to read bytes and decode them into characters.
Common member methods inherited from parent class:
int read() Read a single character and return. int read(char[] cbuf) Read multiple characters at a time and read the characters into the array void close() Close the flow and release all resources associated with it
Construction method:
InputStreamReader(InputStream in) Create a using IDE Default character set( Unicode Character set) InputStreamReader InputStreamReader(InputStream in, String charsetName) Creates a with the specified character set InputStreamReader Parameters: InputStream in: Byte input stream, which is used to read the bytes saved in the file String charsetName: The specified encoding table name is not case sensitive and is used by default UTF-8
Use steps:
1.establish InputStreamReader Object that passes the byte input stream and the specified encoding table name in the construction method 2.use InputStreamReader Methods in objects read read file 3.Release resources matters needing attention: The name of the encoding table specified in the construction method should be the same as the encoding format of the file, otherwise garbled code will be generated
3, Serialized stream
1. Serialized stream
Writing an object to a file in the form of a stream is called writing an object, or serialization of an object.
Objects contain more than just characters, using byte streams
ObjectOutputStream: serialized stream of objects
java.io.ObjectOutputStream extends OutputStream ObjectOutputStream:Serialization stream of object Function: write the object to the file in the form of stream and save it
Construction method:
ObjectOutputStream(OutputStream out) Create write assignments OutputStream of ObjectOutputStream Parameters: OutputStream out: Byte output stream
Unique member methods:
void writeObject(Object obj) Writes the specified object to ObjectOutputStream
Use steps:
1.establish ObjectOutputStream Object, passing byte output stream in construction method 2.use ObjectOutputStream Methods in objects writeObject,Write object to file 3.Release resources
Problems encountered:
Exception thrown: NotSerializableException Introduction to this exception: this exception is thrown when the instance needs to have a serialization interface. This exception is thrown when serializing the runtime or the class of the instance. The parameter should be the name of the class.
Cause of NotSerializableException:
public interface Serializable Class through implementation java.io.Serializable Interface to enable its serialization. A class that does not implement this interface will not be able to serialize or deserialize any of its states.
2. Deserialization stream
Reading out the objects saved in the file in a stream is called reading object, which is also called object deserialization
The read files are saved in bytes, and byte stream is used
ObjectInputStream: deserialized stream of objects
Because the read file can be any type of data, the return value is received with Object type.
java.io.ObjectInputStream extends InputStream ObjectInputStream:Deserialization stream of object Function: read out and use the objects saved in the file in the form of stream
Construction method:
ObjectInputStream(InputStream in) Create from specified InputStream Read ObjectInputStream Parameters: InputStream in: Byte input stream
Unique member methods:
Object readObject() from ObjectInputStream read object
Use steps:
1.establish ObjectInputStream Object to transfer byte input stream in construction method 2.use ObjectInputStream Methods in objects readObject Read the file where the object is saved 3.Release resources 4.Use the read object
Problems encountered:
readObject Method declaration thrown classNotFoundException(class File not found (exception) When no object exists class This exception is thrown when the file is Precondition for deserialization: 1.Class must implement Serializable Interface 2.There must be a corresponding class class file
3. Exception handling
analysis:
1.about JVM To deserialize an object, it must be able to find it class Class of the file. If this class cannot be found class File, a classNotFoundException Abnormal. 2.In addition, when JVM Can be found when deserializing an object class File, but class The file was modified after serializing the object, Then the deserialization operation will also fail and run out of one InvalidClassException Abnormal.
The reason for this exception is:
1.The serial version number of the class does not match the version number of the class descriptor read from the stream 2.The class contains an unknown data type 3.This class has no accessible parameterless constructor
Principle and solution of InvalidClassException exception
The compiler (javac.exe) will Compile java file to generate person Class (bytecode file)
The Person class implements the Serializable interface according to the definition of the class
To person Class file, add a serial number: serialVersionUID=-1234
When serializing, the object is saved in Person.txt Medium: Person{age=18, name='Zhang San'} serialVersionUID=-1234 When deserializing, the Person.class Serial number and in the file Person.txt Compare the serial number in the file. If it is the same, the deserialization is successful If not, a serialization conflict exception will be thrown: InvalidClassException
4.Serializable interface and transient keyword
During serialization and deserialization, NotSerializableException (no serialization exception) will be thrown
Class by implementing Java io. Serializable interface to enable its serialization. A class that does not implement this interface will not be able to serialize or deserialize any of its states.
Serializable interface is also called tag interface:
Classes to serialize and deserialize must implement Serializable Interface, a tag is added to the class When we serialize and deserialize, we will detect whether there is this tag on the class Marked: can serialize and deserialize No tag: cannot serialize or deserialize, will throw NotSerializableException abnormal Serializable There is nothing in the interface. It just plays a role of marking, so it is called marked interface.
Static keyword: static keyword
Static loading takes precedence over non static loading into memory (static loading takes precedence over object entry into memory) cover static Decorated member variables cannot be serialized. All serialized variables are objects, but static variables do not belong to objects. They are shared by all objects private static int age; oos.writeObject(new Person("Zhang San", 18)); Object o = ois.readObject(); Person{age=0, name='Zhang San'} Member variable age cover static After modification, it cannot be serialized, so when it is deserialized, age=0
Transient keyword: transient keyword
cover transient Decorated member variables cannot be serialized So if you don't want to be serialized, use transient Keyword modification, function and static Keywords are the same, but there is no static Meaning of
Causes and solutions of InvalidClassException exception:
reason:
Every time you modify the definition of a class, you will class The file generates a new serial number
Solution:
No matter whether the class definition is modified or not, the new serial number will not be regenerated You can manually add a serial number to the class Format in Serializable Interface regulations: Serializable classes can be created by declaring"serialVersionUID"Field of (this field must be static)( static),Finally( final)of long Type field) explicitly declares its own serialVersionUID: static final long serialVersionUID = 12L; //Constant, cannot be changed
4, Print stream
1.java.io.PrintStream: print stream
PrintStream adds functionality to other output streams, enabling them to easily print various data value representations.
PrintStream features:
1.Only responsible for data output, not data reading 2.Unlike other output streams, PrintStream Never throw IOException 3.There are unique methods: print,println void print(Any type of value) void println(Any type of value and wrap)
Construction method:
PrintStream(File file):The destination of the output is a file PrintStream(OutputStream out): The destination of the output is a byte output stream PrintStream(String fileName): The destination of the output is a file path
2.PrintStream extends OutputStream
Member methods inherited from parent class:
public void close():Close this output stream and free any system resources associated with this stream public void flush():Refresh this output stream and force any buffered output bytes to be written out. public void write(byte[] b):take b.length Bytes writes to this output stream from the specified byte array public void write(byte[] b, int off, int len):Writes from the specified byte array len Byte, offset from off Start output to this output stream public abstract void write(int b):Outputs the specified bytes to the stream
matters needing attention:
If inherited from parent class write Method to write data, the query code table will be displayed when viewing data: 97-> a If you use your own unique method print/println Method write data, write data [output as is]: 97 -> 97
3.static void setOut(PrintStream out)
You can change the destination of the output statement (the flow direction of the print stream)
The output statement is output on the console by default, using system The setout method changes the destination of the output statement to the destination of the print stream passed in the parameter
static void setOut(PrintStream out) Reassign"standard"Output stream.