The input and output functions of Java language are very powerful and flexible. The only drawback is that the input and output codes seem to be very concise, because you often need to wrap many different objects. In the Java class library, the content of the IO part is very large because it involves a wide range of fields: standard input and output, file operation, data streams on the network, string streams, object streams, zip file streams... The purpose of this article is to introduce a detailed explanation of input and output stream examples in JAVA.
The hierarchy of flows
definition:
Java will read the data object into an input stream, and the object to which it can be written is called the output stream. The structure diagram is as follows:
1. Input and output:
Input/Output refers to the input or output of data to a certain device or environment. Any language has the function of input and output. In a Java program, input and output are completed through streams. It is connected to physical devices through a Java input and output system. Although the actual physical devices connected to the input and output streams are different, they can work in the same way. For example, for the input and output of the hard disk, the input and output of the network host, so there will be various input and output problems and solutions for different devices or environments.
2. Stream:
A stream refers to a sequence of data that moves between the input and output of a computer. The data in the stream sequence can be either raw binary data that has not been processed or specific data that meets the requirements of a certain format after a certain encoding process. It is customary to call the part related to the code internal and the part independent of the code external.
From the data transmission method, the stream can be divided into input stream and output stream; from the content of the stream, the stream can be divided into byte stream and character stream.
(1) Input and output stream
The function of the input stream is to read data from the inside of the program to the outside.
The function of the output stream is to write data from outside the program to inside.
(2) Byte Stream and Character Stream
A byte stream can read and write data in units of bytes, which can read and write data from one byte after another, or read and write byte blocks of any length at a time (i.e., byte arrays).
Character streams are used in characters when reading and writing data in streams, one character at a time, or one character block at a time.
In order to facilitate stream processing, streams in the Java language are encapsulated in the java.io package, so to use streams, you must import the java.io package.
Java's I/O stream is based on four abstract classes, namely InputStream, OutputStream, Reader and Writer. The InputStream class and its subclass can be used to implement input processing of byte stream data; the OutputStream class and its subclass can be used to implement output processing of byte stream data; the Reader class and its subclass can be used to implement input processing of character stream data; the Writer class and its subclass can be used to implement output processing of character stream data.
1. File class
Reading and writing files in Java can be implemented through input and output streams, but Java provides a special File class to implement it for file directories, properties, and management information.
(1) The constructor of File class
The constructors for creating a File class object are:
File (String pathname); //Create based on the path name.
File (File parent, String child); //Create under the given File object.
File (String parent, String child); //Create based on the specified path.
File (URL url); //Create based on a URL link.
(2) Common methods of File class
boolean canRead(): determines whether the path corresponding to the File object is readable.
boolean canWrite(): determines whether the path corresponding to the File object is writable.
boolean exists(): determines whether the path corresponding to the File object exists.
String getAbsolutePath(): Gets the absolute path of the corresponding path of the File object.
String getParent(): Gets the directory of the corresponding path of the File object.
String getPath(): Gets the path corresponding to the File object.
boolean isAbsolute(): determines whether the path corresponding to the File object is an absolute path.
String getName(): Gets the file name of the corresponding path of the File object.
boolean isDirectory(): determines whether the path corresponding to the File object is a directory.
boolean isFile(): determines whether the path corresponding to the File object is a file.
boolean isHidden(): determines whether the file corresponding to the File object is a hidden attribute.
long length(): Get the length of the file corresponding to the File object.
long lastModified(): Obtain the latest modification time of the file corresponding to the File object.
boolean renameTo(File dest): Change the file name of the file corresponding to the File object.
boolean setReadOnly(): Set the corresponding file of the File object to read-only.
(3) Create a file
Create a new file by creating a file output stream. This method cannot create a directory, and if the file you want to create already exists, a new file will be created to overwrite the original file.
FileOutrputStream file = new FileOutputStream("filename"); (4) Obtain a file list
Get a file list of a certain folder through the list() or listFiles() method of the File class. There are several forms:
String[] list();
File[] listFiles();
File[] listFiles(FilenameFilter filter);
File[] listFiles(FileFilter filter);
Among them, FileFilter and FilenameFilter are both interfaces, and filter is the corresponding filter. Declare a certain class and implement the filter interface, so that all matching files can be listed through filtering conditions.
2. InputStream class and OutputStream class
The byte stream class is a series of classes derived from the abstract classes InputStream and OutputStream. This type of stream is based on bytes. InputStream and OutputStream classes can be used to process binary file data, but also to process text files.
1. Common methods of InputStream class
The InputStream class is the parent class of all input streams. All methods of this class will throw an IOException when an error occurs. The main methods are:
(1) public abstract int read() those IOException
The method returns an integer between 0 and 255 or -1, and -1 means that the end of the stream has been encountered, and other corresponding bytes read in.
(2) public int read(byte[]b) those IOException
The method reads bytes into the byte array given by the parameter, and the return value is the number of bytes actually read in or -1 (the end of the stream is encountered).
(3) public int read(byte[]b, int i, int b) those IOException
The last two parameters of the method give the starting position of read and the maximum number of bytes read respectively.
(4) public int available()
Returns the number of bytes that have not been read in the current stream object. That is, obtain the length of data in the stream.
(5) public long skip(long n)
Skip n bytes in the current stream object, and the actual number of bytes skipped is returned as a return value.
(6) public boolean markSupported()
Determine whether the flow supports marks, and marks can easily return to the original read position.
(7) public void close()
Close the current stream object and release the resources occupied by the stream object.
(8) public void mark(int i)
Set a flag for the current position in the stream so that you can continue to read from that position later.
(9) public void reset()
Return the position of stream reading to the position of the set mark.
2. Common methods of OutputStream class
The OutputStream class is the parent class of all output streams. All methods of this class return void and throw an IOException in an error case. The main methods are:
(1) public void write(int b) throws IOException
Write a byte of data to the end of the stream.
(2) public void write(byte[] b) throws IOException
Write the data in array b to the current stream object in turn.
(3) public void wire(byte[]b, int i, int n)
Write data of subsequent lengths in the array into the stream object in sequence from the beginning (included).
(4) public void close()
Close the current stream object and release the resources occupied by the stream object.
(5) public void flush()
Force output the buffered data in the current stream object. Use this method to achieve immediate output.
Most methods of the above two classes are overridden by subclasses of InputStream and OutputStream, except for mark() and reset() methods.
3. FileInputStream class
The FileInputStream class is a subclass of InputStream, which can be used to process data streams that use files as data input sources to implement file reading operations.
Its construction methods are:
(1) FileInputStream(File f)
Create a file input stream with the file object f with the specified name as the data source.
If f exists, it should be a file path. If it is a directory, an IOException will be thrown, but if this directory does not exist, it will be thrown: FileNotFoundException will be thrown.
(2) FileInputStream(String name)
Create a file input stream with a file named name as the data source.
(3) FileInputStream(FileDescriptor f)
Create a file input stream for the input end based on the file descriptor object f.
Its main method is to override the methods of the parent class (InputStream class): read(), read(byte[]b), read(byte[]b, int i, int length), skip(long n), available(), close().
4. FileOutputStream class
The FileOutputStream class is a subclass of OutputStream, which is used to process data streams output by files as data, and implement write operations to files. Its construction methods are:
FileOutputStream(File f);
FileOutputStream(File f, boolean b);
FileOutputStream(String f);
Its main methods include methods that cover the parent class: write(int b), write(byte[]b), write(byte[]b, int off, int len), close(), and flush().
5. DataInputStream and DataOutputStream classes
Objects created by DateInputStream and DataOutputStream classes are called data input streams and data output streams, respectively. They implement the DataInput interface and the DataOutput interface respectively. The DateInputStream class and the DataOutputStream object allow reading of various types of Java data.
These two streams belong to filtering streams, and other streams such as InputStream or OutputStream are often used as their input or output. For example:
FileInputStream fis = new FileInputStream("d://a.txt");
DataInputStream dis = new DataInputStream(fis);
FileOutputStream fos = new FileOutputStream("d://a.txt");
DataOutputStream dos = new DataOutputStream(fos);
The input and output of DateInputStream and DataOutputStream are almost corresponding. The reading and writing methods of each basic data type can be identified from its suffix name. For example:
readInt(), writeInt() // Read and write an int value
readBoolean(), writeBoolean() // Read and write a boolean value
readChar(), writeChar() // Read and write a character
readDouble(), writeDouble() // Read and write a double precision floating point value
readFloat(), writeFloat() // Read and write a single-precision floating-point value
WriteChars() // Write a string, but there is no way to read the string directly
3. Reader class and Writer class
Characters in Java use Unicode encoding, each character has two bytes, that is, 16 bits. Character streams are based on characters represented by 16-bit Unicode codes, and read and write text data, which can realize the conversion between internal formats in Java programs and external formats such as text files, display outputs, keyboard inputs, etc. This method is especially suitable for the operation of Chinese characters. If Chinese characters operate in bytes, it is possible to output garbled code.
Reader and Writer are abstract parent classes of all character streams in the java.io package, defining key methods to implement other stream classes. The two most important ones are read() and write(), which read and write character data respectively. The methods of Reader and Writer classes and their subclasses are very similar to the methods of using InputStream classes, OutputStream classes and their subclasses. But the parameters in it are replaced with characters or character arrays.
1. Common methods of Reader class and Writer class
The Reader class is an abstract class. All methods of this class will throw an IOException exception under error conditions. Common methods are as follows:
(1) abstract void close(): close the input source.
(2) void mark(int numChars): Place a mark to the current point of the input source.
(3) boolean markSupported(): If this stream supports the mark/reset method, true will be returned.
(4) int read(): Read a single character.
(5) int read(char[] buf): read characters into character array.
(6) abstract int read(char[] buf, int offset, int numChars): Read characters into a part of the array.
(7) boolean ready(): Return true if the next input request does not have to wait, otherwise return false.
(8) void reset(): Reset the input pointer to the marked set before.
(9) long skip(long numChars): skip n character input and return the actual number of characters skipped.
The Writer class is also an abstract class, and the commonly used methods are as follows:
(1) abstract void close(): close the output stream.
(2) abstract void flush(): Determine the output status to clear any cache.
(3) void write(int ch): Write a single character.
(4) void write(char[] buf): write to a character array.
(5) abstract void write(char[] buf, int offset, int numChars): write part of the character array.
(6) void write(String str): write a string.
(7) void write(String str, int offset, int numChars): write part of the string.
2. FileReader class
The FileReader class inherits from the InputStreamReader class, and the InputStreamReader class inherits from the Reader class. Therefore, the methods provided by the Reader class and the InputStreamReader class can be used for objects created by the FileReader class. The constructor methods of FileReader are:
FileReader(File file);
FileReader(FileDescriptor e);
FileReader(String filename);
3. FileWriter class
The FileWriter class inherits from the OutputStreamWriter class, and the OutputStreamWriter class inherits from the Writer class. Therefore, the methods provided by the Writer class and the OutputStreamWriter class can be used by the objects created by the FileWriter class. The constructor methods of FileWriter are:
FileWrite(File filePath);
FileWrite(File f, boolean append);
FileWrite(FileDescriptor e);
FileWrite(String filename);
FileWrite(String filename,boolean append);
4. BufferedReader class
The BufferedReader class inherits from the Reader class, which is used to read data in the buffer. The BufferedReader class belongs to filtering streams, and other streams such as FileReader are often used as their input or output. Its construction methods are:
BufferedReader(Reader in);
BufferedReader(Reader in, int bufSize);
For example:
FileReader fr=new FileReader("d:/1.txt");
BufferedReader buf = new BufferedReader(fr);
BufferedReader provides the readerLine() method to read every line of text.
5. BufferedWriter class
The BufferedWriter class inherits from the Writer class, and the BufferedWriter class is used to write data into the buffer. Using the BufferedWriter class is similar to using the BufferedReader class. The difference is that the data in the buffer must be cleared by flush() method in the end, that is, write all the data in the buffer into the file. Its construction methods are:
BufferedWriter(Writer out);
BufferedWriter(Writer out, int bufSize);
4. RandomAccessFile class
Random file access in Java requires the use of the RandomAccessFile class (this class allows access from any location, not only read, but also write), which directly inherits from the Object class and implements the interfaces DataInput and DataOutput.
Since the RandomAccessFile class implements all methods defined in the DataInput and DataOutput interfaces, it can read basic type data from the file and write basic type data to the file. In addition to the methods defined in the DataInput and DataOutput interfaces, the RandomAccessFile class also defines some other methods to support random access.
The stream created by the RandomAccessFile class is different from the previous input and output streams. The RandomAccessFile class is neither a subclass of the InputStream class in the input stream class, nor a subclass of the OutputStream class in the output stream class. However, the direction of the stream created by the RandomAccessFile class can be used as both a source and a destination. In other words, when reading and writing a file, you can create a RandomAccessFile stream pointing to the file, so that you can read the data of the file from the stream and write data to the file through the stream.
Two constructor methods of RandomAccessFile class:
(1) RandomAccessFile(String name, String mode)
The parameter name is used to determine a file name, giving the source (also the flow destination) of the created stream, and the parameter mode takes r (read-only) or rw (read-writeable), which determines the access rights of the created stream to the file.
(2) RandomAccessFile(File file, String mode)
The parameter file is a File object, which gives the source (also the destination of the stream). The parameter mode takes r (read-only) or rw (read-writeable), and determines the access rights of the created stream to the file. When creating an object, the FileNotFoundException should be caught; when the stream performs read and write operations, the IOException should be caught.
The method of reading and writing information of the object RandomAccessFile is the same as the method of input and outputting the data object. It can access all read() and write() methods in the classes DataInputStream and DataOutputStream.
How to move file read and write pointers:
(1) long getFilePointer(): Returns the current location of the file pointer.
(2) void seek(long pos): Place the file pointer in the specified absolute position. The position value is calculated as the byte offset pos from the start of the file. Pos is 0, which represents the beginning of the file.
(3) long length(): Returns the length of the file. The position value is length(), which represents the end of the file.