Introduction: In IO stream learning, we usually encounter some binary file copy problems, such as a picture, a video, may be our class bytecode file, they are the typical use of binary code implementation of the file. So how can we use our IO stream knowledge to solve the binary copy problem? The answer is that you need to implement classes DataOutputStream and DataInputStream. Here’s how to use these two classes.

DataInputStream and DataOutputStream

DataInputStream and DataOutputStream are subclasses of FilterOutputStream and implement the DataOutput interface. They have important constructors DataInputStream (inputStream in) respectively. And DataOutputStream(outputStream out), which are primarily the methods we use to read and output binaries.

Two, implementation steps

1. Requirement contentThe first step is to check whether the directory exists, create it if it does not, and then construct objects for InputStream and OutputStream.

In the second step, DataInputStream and DataOutputStream are constructed after the object is constructed. In the construction process, the constructor is used to pass InputStream and OutputStream objects.

The third step is to construct a byte array to store the data read in. The length I define directly is the length of the file size, because the size of the byte array is very large, with the size of 2 to the power of the power, which is sufficient for ordinary files.

Step 4. Read and write data using the read() and write() methods of DataInputstream and DataOutputStream

Step 5, don’t forget to turn off the open stream.

After the success of the file is copied, can open a new file, can have a look at your pictures, according to the normal here to spread a little knowledge, is the computer file suffix is mainly for the convenience of system to identify the use what software to open the file, such as JPG file is to use photo editor open, TXT file is to use notepad to open.

The code is as follows (example) :

Conclusion:

DataInputStream and DataOutputStream objects are used to read and write files to and from binary files. Other binary file copies are much the same.

Creation is not easy, helpful small partners help point a thumbs-up, the blogger thank you, love you!!