Basic IO operations
1. InputStream and OutputStream1.1. Input and output
The program we write, in addition to defining some of the data itself, often references external data or sends its own data to the outside world. For example, the program we write wants to read a text file, or we want to write some data from the program to a file. At this point we will use the input and output.
- What is input: input is a direction from the outside into the program, usually we need to "read" the external data when using the input. So the input is used to read the data.
- What is output: The output is a direction from the program sent to the outside world, usually we need to "write" the data to the outside world, using the output. So the output is used to write the data.
1.2. Node flow and processing flow
- According to whether the stream is directly connected with a specific place (such as disk, memory, device, etc.), it is divided into two types: node stream and processing stream.
① node stream: You can read and write data from or to a specific place (node).
② processing Flow: Is the connection and encapsulation of an existing stream, which implements the data read and write through the function invocation of the encapsulated stream.
- The construction of the process flow always takes an additional stream object to do the argument.
- A Stream object passes through multiple wrappers of other streams, called links to streams.
1.3. InputStream and OutputStream Common methods
InputStream is the parent class of all byte input streams, which defines the underlying read method, which is commonly used as follows: int read()
Reads a byte, returned as an int, the "low eight-bit" of the int value is valid, or EOF if the return value is-1.
int read(byte[] d)
Attempts to read up to the length of the given array and to the array, and the return value is the amount of bytes actually read.
The OutputStream is the parent of all byte output streams, which defines the underlying writing method, which is commonly used as follows:
void write(int d)
Write a byte that writes "Low eight bits" of the given int
void write(byte[] d)
Writes out all the bytes in the given byte array.
2. File Stream 2.1. Create a FIS Object
FileInputStream is a byte input stream of a file that we use to read the contents of a file in bytes.
FileInputStream has two common construction methods:
①fileinputstream (file file):
Creates a file that is used to read the files represented by the given file object. fis
For example:
Filefile =newFile("demo.dat");FileInputStream fis=newFileInputStream(file);//创建一个用于读取demo.dat文件的输入流
②fileinputstream (String name):
Creates the FIS that are used to read the file specified by the path name in the given file system name
For example
//创建一个用于读取demo.dat文件的输入流=newFileInputStream("demo");
2.2. Create Fos object (override mode)
FileOutputStream is the byte output stream of a file that we use to write data to a file in bytes.
Construction Method:
① FileOutputStream(File file):
Creates a file output stream that writes data to the file that is represented by the specified Files object.
For example:
FIlefile =newFile("demo.dat");FileOutputStream fos =newFileOutputStream(file);
② FileOutputStream(String filename):
Creates an output file stream that writes data to a file with the specified name.
For example:
FileOutputStream fos =newFileOutputStream("demo.dat");
- If the specified file already contains content, the original data in the file is purged when the data is written to it using the FOS.
2.3. Create Fos object (Append mode)
The FOS created by the construction method of the previous section overwrites the original data in the file when it is written to the file. To append new data after the file's original data requires the following construction method to create the FOS
Construction Method:
① FileOutputStream(File file,boolean append):
Creates a file output stream that writes data to the file that is represented by the specified Files object.
For example:
Filefile =newFile("demo.dat");FileOutputStream fos =newFileOutputStream(file,true);
② FileOutputStream(String filename,boolean append):
Creates an output file stream that writes data to a file with the specified name.
For example:
FileOutputStream fos =newFileOutputStream("demo.dat",true);
- Of the above two constructor methods, if the second parameter is true, the data written through the FOS is appended to the end of the file.
2.4. Read () and write (int D) methods
-
FileInputStream inherits from InputStream, which provides a method for reading file data in bytes read.
int read()
Reads a data byte from this input stream, and returns 1 for EOF (End of File).
-
FileOutputStream inherits from OutputStream, which provides a way to write data in bytes to a file.
void write(int d)
Writes the specified bytes to this file output stream. , this refers to the "low eight bits" of the given int value.
For example
fos.write(‘A‘);//这里要注意,char占用2个字节,但这里只写入了1个字节。
2.5. Read (byte[] D) and write (byte[] D) methods
FileInputStream also supports the method of bulk reading byte data:
int read(byte[] b)
Reads a maximum of b.length bytes of data from this input stream into a byte array
FileOutputStream also supports the method of bulk writing byte data:
void write(byte[] d)
Writes a b.length byte from the specified byte array to this file output stream.
For example:
FileOutputStream fos =newFileOutputStream("demo.txt");byte[] data ="HelloWorld".getBytes();fos.write(data);//会将HelloWorld的所有字节写入文件。 void write(byte[] d,int offset,int len)//将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
For example:
FileOutputStream fos =newFileOutputStream("demo.txt");bytedata ="HelloWorld".getBytes();fos.write(data,5,5);//只会将world这5个字节写入文件。
3. Buffer Stream 3.1. BIS Basic Working principle
Reading data in bytes, if read data, can result in too frequent reads and greatly reduce the read efficiency. For this we can improve the efficiency of reading by increasing the number of bytes read at a time to reduce read and write times.
- The Bufferedinputstream is a buffered byte input stream. It internally maintains a buffer (a byte array) that, when reading a byte, reads a number of bytes at a time and buffers it as much as possible, then returns the bytes one by one until the data in the buffer is fully read, and then repeats itself again by reading several bytes. This reduces the number of reads, which improves read efficiency.
- The BIS is a processing stream that provides us with buffering capabilities.
3.2. BOS Basic Working principle
Similar to buffered input streams, when writing to a hardware device, increasing the number of writes will undoubtedly reduce the writing efficiency, so we can use the buffered output stream to write some data in a single batch to reduce write times to improve the writing efficiency.
- A buffer is also maintained inside the Bufferedoutputstream buffered output stream, and whenever we write data to the stream, the data is first stored in a buffer, and when the buffer is full, the buffer stream writes the data all at once.
3.3. Buffered input and output using BIS and BOS
Use buffered streams for file replication:
FileInputStream fis =newFileInputStream("java.zip");BufferedInputStream bis =newBufferedInputStream(fis);FileOutputStream fos =newFileOutputStream("copy_java.zip");BufferedOutputStream bos =newBufferedOutputStream(fos);int d =-1;while((d = bis.read())!=-1){ bos.write(d);}bis.close();//读写完毕后要关闭流,只需要关闭最外层的流即可bos.close();
3.4. Flush method
The use of buffered output streams can improve writing efficiency, but there is also the problem of writing data without immediacy. Sometimes we need to do some writing and we want to write this data out, not in the buffer until the buffer is full. At this point we can flush with a method of buffering the stream.
void flush()
Clears the buffer and forces the data in the buffer to be written out.
For example:
BufferedOutputStream bos=newBufferedOutputStream(newFileOutputStream("demo.dat"));bos.write(‘a‘);//并没有向磁盘写出,而是写入到了BOS的缓存中bos.flush();//强制将缓存中的数据一次性写出,这时‘a’才会被写入磁盘bos.close();//实际上,close()方法在变比缓冲流前也调用了flush()
4. Object Flow
The object is present in memory. Sometimes we need to save the object to the hard disk, and sometimes we need to transfer the object to another computer and so on. At this point we need to convert the object to a sequence of bytes, and this process is called object serialization. Instead, we have a sequence of bytes that needs to be converted to the corresponding object, and this process is called deserialization of the object.
4.1. Implementing object serialization using Oos
ObjectOutputStream is the output stream used to serialize an object.
The methods for implementing object serialization are:
void writeObject(Object o)
The method can be written out after converting the given object to a sequence of bytes.
For example:
Emp emp =newEmp("张三",12,"男");FileOutputStream fos =newFileOutputStream("Emp.obj");ObjectOutputStream oos =newObjectOutputStream(fos);oos.writeObject(emp);//将emp对象序列化后写入文件oos.close();
4.2. Implementing object deserialization using Ois
ObjectInputStream is the input stream used to deserialize an object.
Its implementation of the object deserialization method is:
ObjectreadObject()
The method can read bytes from the stream and convert to the corresponding object.
For example:
FileInputStream fis =newFileInputStream("Emp.obj");ObjectInputStream ois =newObjectInputStream(fis);Emp emp =(Emp)ois.readObject();//将Emp对象从文件中读取并反序列....ois.close();
4.3. Serializable interface
-
ObjectOutputStream there is a requirement when serializing an object that the class to which the object needs to be serialized must implement the Serializable interface.
-
Implementing this interface does not require overriding any methods. It is simply a token that can be serialized.
- A class that typically implements the interface needs to provide a constant serialversionuid that indicates the version of the class. If the declaration is not displayed, the default Serialversionuid of the class is computed for each aspect of the current class when the object is serialized, but different platform compiler implementations differ, so the declaration version number should be displayed for cross-platform.
- If the declared class is serialized on top of the hard disk, and then changes the properties of the category (Increase or decrease or rename) as the requirements change, the invalidclassexception occurs when deserializing, which creates an incompatibility problem. But when the serialversionuid is the same, it deserializes the different field with the default value of type to avoid incompatibility issues.
For example:
publicclass Emp implements Serializable{privatestaticfinal long serialVersionUID =1L;privateString name;private int age;privateString gender;//getter and setter and other...}
4.4. Transient keywords
The sequence of bytes obtained by the object is often large, and sometimes we can ignore some unnecessary attributes when serializing an object, thus "slimming" the resulting sequence of bytes.
keyword transient
Attributes that are decorated by this keyword are ignored when serialized.
For example:
publicclass Emp implements Serializable{privatestaticfinal long serialVersionUID =1L;privateString name;privatetransient int age;//该属性在序列化时会被忽略privateString gender;//getter and setter and other...}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Dark Horse programmer--java base--io basic operation