Thinking logic of computer programs (57) and thinking 57
This section describes how to process files in binary bytes in Java. we mentioned the concept of stream in Java in the previous section. The main streams read and write in binary mode include:
- InputStream/OutputStream: This is the base class and they are abstract classes.
- FileInputStream/FileOutputStream: The Input Source and output target are file streams.
- ByteArrayInputStream/ByteArrayOutputStream: The Input Source and output target streams are byte arrays.
- DataInputStream/DataOutputStream: Decorative class that reads and writes streams by basic type and string instead of just byte.
- BufferedInputStream/BufferedOutputStream: Decorative class that provides the buffer function for input and output streams.
Next, we will introduce the functions, usage, principles, and scenarios of these classes. Finally, we will summarize some simple practical methods.
InputStream/OutputStream
Basic Method of InputStream
InputStream is an abstract class. The main method is:
public abstract int read() throws IOException;
Read reads the next byte from the stream. The return type is int, but the value ranges from 0 to 255. When the stream ends, the return value is-1. If no data exists in the stream, the read method is blocked until the data arrives, the stream is closed, or an exception occurs. When an exception occurs, the read method throws an exception of the IOException type. This is a checked exception and must be processed by the caller. Read is an abstract method, and the specific subclass must be implemented. FileInputStream calls the local method. The so-called local method is generally not written in Java and is mostly implemented in C language, the specific implementation is often related to virtual machines and operating systems.
InputStream also has the following method to read multiple bytes at a time:
public int read(byte b[]) throws IOException
The read bytes are placed in the parameter array B. The first byte is stored in B [0], the second in B [1], and so on. the maximum number of bytes read at a time is the length of array B, however, the actual number of bytes read may be smaller than the array length, and the returned value is the actual number of bytes read. If the stream ends at the beginning of reading,-1 is returned. Otherwise, as long as the array length is greater than 0, this method will try to read at least one byte. If no byte exists in the stream, it will block and throw IOException when an exception occurs. This method is not an abstract method. InputStream has a default implementation, which is mainly to call the read method of reading a byte cyclically. However, sub-classes such as FileInputStream often provide more efficient implementation.
There is also a more common overload method for batch reading:
public int read(byte b[], int off, int len) throws IOException
The first byte to be read is put into B [off]. A maximum of len bytes can be read. read (byte B []) is to call this method:
public int read(byte b[]) throws IOException { return read(b, 0, b.length);}
When the stream reading is complete, it should be closed to release related resources. The method of closing the stream is as follows:
public void close() throws IOException
The close method should be called no matter whether the read method throws an exception. Therefore, close should be placed in the finally statement. Close itself may also throw an IOException, but it can usually be captured and ignored.
Advanced method of InputStream
InputStream also defines the following methods:
public long skip(long n) throws IOExceptionpublic int available() throws IOExceptionpublic synchronized void mark(int readlimit)public boolean markSupported()public synchronized void reset() throws IOException
Skip skips n bytes in the input stream. because the number of remaining bytes in the input stream may be less than n, the return value is the number of actually skipped bytes. By default, InputStream tries its best to read n Bytes and throw them away. subclasses often provide more efficient implementations, and FileInputStream calls local methods. When processing data, the skip address is more efficient than reading and throwing away the data that you are not interested in.
Available returns the approximate number of bytes that can be read without blocking the next time. The default Implementation of InputStream is to return 0. The subclass will return the appropriate value based on the actual situation, and FileInputStream will call the local method. In file read/write, this method is generally useless, but when reading data from the network, you can read the data only when there is enough data in the network according to the return value of this method to avoid blocking.
Generally, stream reading is one-time and can only be performed forward, but cannot be performed backward. However, you may want to read the subsequent content first and then read it again based on the actual situation. For example, to process an unknown binary file, we are not sure about its type, but it may be determined by the first dozens of bytes of the stream. After being interpreted, It is reset to the beginning of the stream, to the corresponding type of code for processing.
InputStream defines three methods, mark/reset/markSupported, to support repeated reading from read streams. How can I read it again? First, mark the current position using the mark method. When reading some bytes and reading from the marked position again, call the reset method.
Repeated reading does not mean that the mark can be returned to any mark location. The mark method has the readLimit parameter, which indicates the maximum number of bytes that can be read from the future after the mark is set. If it exceeds, the tag is invalid. Why? Because the stream can be re-viewed, because it can save the bytes starting from the mark position, and the memory consumed for saving cannot be infinitely large, and the stream must not be less than readLimit.
Not all streams support mark/reset. You can determine whether mark/reset can be returned by markSupported. InpuStream is not supported by default, and FileInputStream is not supported directly, but BufferedInputStream and ByteArrayInputStream can.
OutputStream
The basic method of OutputStream is:
public abstract void write(int b) throws IOException;
Write a byte to the stream. Although the parameter type is int, only the lowest 8 bits are used. This method is an abstract method. The specific subclass must be implemented. FileInputStream will call the local method.
OutputStream also has two batch writing methods:
public void write(byte b[]) throws IOExceptionpublic void write(byte b[], int off, int len) throws IOException
In the second method, the first written byte is B [off], the number of writes is len, and the last is B [off + len-1]. The first method is equivalent to calling: write (B, 0, B. length );. The default Implementation of OutputStream is to call the write method of a single byte cyclically, and subclass is often more efficient. FileOutpuStream calls the corresponding local method for batch writing.
There are two methods for OutputStream:
public void flush() throws IOExceptionpublic void close() throws IOException
Flush writes buffered but not actually written data. For example, in BufferedOutputStream, calling flush will write the buffer content to the decorated stream, and call the flush method of the stream. The base class OutputStream has no buffer, and the flush code is empty.
It should be noted that FileOutputStream is the output stream of the file. You may think that calling flush will forcibly ensure that the data is saved to the hard disk, but this is not the case. FileOutputStream has no buffer and does not overwrite flush, calling flush has no effect. Data is transmitted to the operating system, but it is not certain when the operating system is saved to the hard disk. To ensure that the data is saved to the hard disk, you can call the special method in FileOutputStream.
Close usually calls flush first, and then releases the system resources occupied by the stream. Like InputStream, close should generally be placed in finally statements.
FileInputStream/FileOutputStream
FileOutputStream
The main construction methods of FileOutputStream include:
public FileOutputStream(File file) throws FileNotFoundExceptionpublic FileOutputStream(File file, boolean append) throws FileNotFoundExceptionpublic FileOutputStream(String name) throws FileNotFoundExceptionpublic FileOutputStream(String name, boolean append) throws FileNotFoundException
There are two types of parameters: File path, which can be the file object or File path name. The path can be an absolute or relative path. If the file already exists, the append parameter specifies whether to append or overwrite. "true" indicates append, and "no append" indicates overwrite. A new FileOutputStream object will actually open the file, and the operating system will allocate relevant resources. If the current user does not have the write permission, an exception SecurityException is thrown, which is a RuntimeException. If the specified file is an existing directory or the file cannot be opened for other reasons, an exception FileNotFoundException is thrown, which is a subclass of IOException.
Let's look at a simple piece of code to write the string "hello, 123, old horse" to the hello.txt file:
OutputStream output = new FileOutputStream ("hello.txt"); try {String data = "hello, 123, lauma"; byte [] bytes = data. getBytes (Charset. forName ("UTF-8"); output. write (bytes);} finally {output. close ();}
OutputStream can only write files in byte or byte arrays. To write strings, we call the getBytes method of String to get its UTF-8 encoded byte array, and then call the write method, the write process is placed in the try statement and the close method is called in the finally statement.
FileOutputStream has two additional methods:
public FileChannel getChannel()public final FileDescriptor getFD()
FileChannel is defined in java. nio, which indicates the file channel concept. We will not introduce the channel in depth, but the memory ing file method is defined in FileChannel. We will introduce it in subsequent chapters. FileDescriptor indicates the file descriptor, which is connected to some File Memory Structures of the operating system. In most cases, we will not use it, but it has a method of sync:
public native void sync() throws SyncFailedException;
This is a local method that ensures that the data buffered by the operating system is written to the hard disk. Note that it is different from the flush method of OutputStream. flush only writes the data buffered by the application to the operating system, and sync ensures that the data is written to the hard disk. However, in general, we do not need to call it manually, data will be written sooner or later as long as there is no problem with the operating system and hardware devices. However, this method can be called to ensure that data is written to the hard disk under certain circumstances.
FileInputStream
The main construction methods of FileInputStream include:
public FileInputStream(String name) throws FileNotFoundExceptionpublic FileInputStream(File file) throws FileNotFoundException
The parameter is similar to FileOutputStream. It can be a File path or File object, but it must be an existing File, not a directory. A new FileInputStream object will actually open the file, and the operating system will allocate relevant resources. If the file does not exist, an exception FileNotFoundException will be thrown. If the current user does not have the read permission, an exception SecurityException will be thrown.
Let's look at a simple piece of code, read the file "hello.txt" written above into the memory and output it:
InputStream input = new FileInputStream("hello.txt");try{ byte[] buf = new byte[1024]; int bytesRead = input.read(buf); String data = new String(buf, 0, bytesRead, "UTF-8"); System.out.println(data);}finally{ input.close();}
The read is a byte array. We use the String constructor with encoded parameters to convert it to a String. This Code assumes that all content is read by a read call and the length of the byte cannot exceed 1024. To ensure that all content is read, you can read data in bytes one by one until the end of the file:
int b = -1;int bytesRead = 0;while((b=input.read())!=-1){ buf[bytesRead++] = (byte)b;}
When there is no buffer, the reading performance of one byte is very low. You can use batch reading to ensure that the end of the file is read, as shown below:
byte[] buf = new byte[1024];int off = 0;int bytesRead = 0;while((bytesRead=input.read(buf, off, 1024-off ))!=-1){ off += bytesRead;} String data = new String(buf, 0, off, "UTF-8");
However, it is assumed that the object content length cannot exceed a fixed size of 1024. If you are not sure about the length of the file content, you do not want to allocate a large byte array at a time, but want to read all the file content. How can this problem be solved? You can use ByteArrayOutputStream.
ByteArrayInputStream/ByteArrayOutputStream
ByteArrayOutputStream
The output target of ByteArrayOutputStream is a byte array. The length of this array is dynamically expanded based on the data content. It has two constructor methods:
public ByteArrayOutputStream()public ByteArrayOutputStream(int size)
The size in the second constructor specifies the initial array size. If it is not specified, the length is 32. In the process of calling the write method, if the array size is not enough, it will be extended. The extension policy is also exponential expansion, which is at least doubled each time.
ByteArrayOutputStream can be easily converted to byte arrays or strings by using the following methods:
public synchronized byte[] toByteArray()public synchronized String toString()public synchronized String toString(String charsetName)
The toString () method uses the default encoding.
Data in ByteArrayOutputStream can also be easily written to another OutputStream:
public synchronized void writeTo(OutputStream out) throws IOException
ByteArrayOutputStream also has the following additional methods:
public synchronized int size()public synchronized void reset()
Size returns the number of bytes currently written. The reset resets the number of bytes to 0. After reset, You can reuse the allocated array.
Using ByteArrayOutputStream, we can improve the code of the above read file to ensure that all the file content is read:
InputStream input = new FileInputStream("hello.txt");try{ ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int bytesRead = 0; while((bytesRead=input.read(buf))!=-1){ output.write(buf, 0, bytesRead); } String data = output.toString("UTF-8"); System.out.println(data);}finally{ input.close();}
The read data is first written into ByteArrayOutputStream. After reading the data, call its toString method to obtain the complete data.
ByteArrayInputStream
ByteArrayInputStream packs the byte array into an input stream. It is an adapter Mode and Its constructor methods include:
public ByteArrayInputStream(byte buf[])public ByteArrayInputStream(byte buf[], int offset, int length)
The second constructor uses the offset in the buf to start length bytes. All data of ByteArrayInputStream is stored in the memory and can be read repeatedly by mark/reset.
Why is byte array converted to InputStream? This is similar to the reason for converting an array and a single element into a container interface in the container class. Many codes are constructed using InputStream/OutputSteam as parameters, which constitute a collaboration system, converting byte arrays into InputStream can easily participate in this system and reuse code.
DataInputStream/DataOutputStream
The classes described above can only be read and written in bytes. How can I read and write data of other types? For example, int or double. You can use DataInputStream/DataOutputStream, which are decorative classes.
DataOutputStream
DataOutputStream is a subclass of the base class FilterOutputStream of the decoration class, And FilterOutputStream is a subclass of OutputStream. Its construction method is as follows:
public FilterOutputStream(OutputStream out)
It accepts an existing OutputStream and basically delegates all operations to it.
DataOutputStream implements the DataOutput interface, which can write data with various basic types and strings. Some methods are as follows:
void writeBoolean(boolean v) throws IOException;void writeInt(int v) throws IOException;void writeDouble(double v) throws IOException;void writeUTF(String s) throws IOException;
When writing data, DataOutputStream converts these types of data to their corresponding binary bytes, for example:
- WriteBoolean: Write a byte. If the value is true, write 1; otherwise, 0.
- WriteInt: Four bytes are written. The maximum byte is written first, and the last byte is written.
- WriteUTF: Write the UTF-8 encoding byte of the string, the encoding format is slightly different from the standard UTF-8 encoding, but we don't have to worry about this detail.
Like FilterOutputStream, DataOutputStream constructor also accepts an existing OutputStream:
public DataOutputStream(OutputStream out)
Let's take an example to save a student list to a file. The student category is defined:
class Student { String name; int age; double score; public Student(String name, int age, double score) { ... } ...}
The constructor and getter/setter methods are omitted. The student list content is:
List <Student> students = Arrays. asList (new Student [] {new Student ("Zhang San", 18, 80.9d), new Student ("Li Si", 17, 67.5d )});
Code that writes the list content to the file students. dat can be:
public static void writeStudents(List<Student> students) throws IOException{ DataOutputStream output = new DataOutputStream( new FileOutputStream("students.dat")); try{ output.writeInt(students.size()); for(Student s : students){ output.writeUTF(s.getName()); output.writeInt(s.getAge()); output.writeDouble(s.getScore()); } }finally{ output.close(); }}
We first write the length of the list, and then call the corresponding write method for each student and field according to its type.
DataInputStream
DataInputStream is a subclass of the base class FilterInputStream of the decoration class, And FilterInputStream is a subclass of InputStream.
DataInputStream implements the DataInput interface, which can read data with various basic types and strings. Some methods are as follows:
boolean readBoolean() throws IOException;int readInt() throws IOException;double readDouble() throws IOException;String readUTF() throws IOException;
When reading data, DataInputStream reads data in byte and converts it to the corresponding type.
The constructor of DataInputStream accepts an InputStream:
public DataInputStream(InputStream in)
Let's take the above student list as an example to see how to read it from the file:
public static List<Student> readStudents() throws IOException{ DataInputStream input = new DataInputStream( new FileInputStream("students.dat")); try{ int size = input.readInt(); List<Student> students = new ArrayList<Student>(size); for(int i=0; i<size; i++){ Student s = new Student(); s.setName(input.readUTF()); s.setAge(input.readInt()); s.setScore(input.readDouble()); students.add(s); } return students; }finally{ input.close(); }}
It is basically a write inverse process. The code is relatively simple and will not be repeated.
Using DataInputStream/DataOutputStream to read and write objects is flexible but troublesome. Therefore, Java provides a serialization mechanism, which we will introduce in subsequent chapters.
BufferedInputStream/BufferedOutputStream
FileInputStream/FileOutputStream has no buffer. The read/write performance by single byte is relatively low. Although it can be read by byte array to Improve the Performance, sometimes it must be read and written by byte, for example, the preceding DataInputStream/DataOutputStream packages the file stream and calls the single-byte read/write method of the file stream. How can this problem be solved? The method is to package the file stream into the buffer stream.
BufferedInputStream has an internal byte array as the Buffer Zone. When reading data, it reads data from the buffer zone first. After reading the buffer zone, it calls the encapsulated stream read. Its constructor has two methods:
public BufferedInputStream(InputStream in)public BufferedInputStream(InputStream in, int size)
Size indicates the buffer size. If not, the default value is 8192.
In addition to improving performance, BufferedInputStream also supports mark/reset and can be read repeatedly.
Like BufferedInputStream, BufferedOutputStream has two constructor methods. The default buffer size is also 8192. Its flush method writes the buffer content to the packaged stream.
When FileInputStream/FileOutputStream is used, the corresponding buffer class should be almost always included in its outer package, as shown below:
InputStream input = new BufferedInputStream(new FileInputStream("hello.txt"));OutputStream output = new BufferedOutputStream(new FileOutputStream("hello.txt"));
For example:
DataOutputStream output = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("students.dat")));DataInputStream input = new DataInputStream( new BufferedInputStream(new FileInputStream("students.dat")));
Practical Method
It can be seen that even if the stream is read and written in binary bytes, Java also includes many classes. Although it is flexible, for some simple requirements, a lot of code needs to be written. In actual development, some common functions are often encapsulated to provide simpler interfaces. Below we provide some practical methods for your reference.
Copy
Copy the content of the input stream to the output stream. The Code is as follows:
public static void copy(InputStream input, OutputStream output) throws IOException{ byte[] buf = new byte[4096]; int bytesRead = 0; while((bytesRead = input.read(buf))!=-1){ output.write(buf, 0, bytesRead); }}
Read files into byte Arrays
Code:
public static byte[] readFileToByteArray(String fileName) throws IOException{ InputStream input = new FileInputStream(fileName); ByteArrayOutputStream output = new ByteArrayOutputStream(); try{ copy(input, output); return output.toByteArray(); }finally{ input.close(); }}
This method calls the copy method above.
Write a byte array to a file
public static void writeByteArrayToFile(String fileName, byte[] data) throws IOException{ OutputStream output = new FileOutputStream(fileName); try{ output.write(data); }finally{ output.close(); }}
Apache has a class library, Commons IO, which provides many easy-to-use methods. It can be used in actual development.
Summary
This section describes how to read and write files in binary bytes in Java and describes the main streams.
- InputStream/OutputStream: it is an abstract base class and has a lot of stream-oriented code. They are used as parameters, such as the copy method described in this section.
- FileInputStream/FileOutputStream: the source and destination of the stream are files.
- ByteArrayInputStream/ByteArrayOutputStream: the source and destination are byte arrays. As the input is equivalent to the adapter, dynamic arrays are encapsulated as the output for ease of use.
- DataInputStream/DataOutputStream: Decorative class that reads and writes streams by basic type and string.
- BufferedInputStream/BufferedOutputStream: Decorative class that provides buffering. FileInputStream/FileOutputStream should always be decorated with this class.
Finally, we provide some practical methods to facilitate common operations. In actual development, we can consider using specialized class libraries such as Apache Commons IO.
The stream introduced in this section is not applicable to text files. For example, the stream cannot be processed by line, and there is no encoding concept. In the next section, let's take a look at the text file and the ghost stream.
----------------
For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Retain All copyrights with original intent.