Java-input/output stream, java-Input/Output
JAVA-input/output stream
1, Input and output:
Input/Output refers to the Input or Output of data on a device or environment. all languages have the input and output functions. In Java programs, input and output are completed through a stream. It is connected to a physical device through the Java input and output system, although the input and output streams are connected to different physical devices, they can work in the same way. for example, the input and output of hard disks and network hosts are input and output. Therefore, there are various input and output problems and solutions for different devices or environments.
2, Stream:
A stream is a data sequence that moves between input and output of a computer. the data in a stream sequence can be either raw binary data that has not been processed, or specific data that has been encoded to conform to certain formats. traditionally, the code-related part is called internal, and the code-independent part is called external.
Based on the data transmission mode, streams can be divided into input streams and output streams. Based on the stream content, streams can be divided into byte streams and upstream streams.
(1)Input and Output streams
The input stream reads data from outside the program.
The output stream is used to write data from outside the program.
(2)Byte stream and byte stream
Byte stream reads and writes data in bytes. It can read and write data from one byte to one byte, you can also read and write bytes of any length at a time (that is, the byte array ).
Character stream (character stream) reads and writes data in a stream in units of characters, one character at a time, or one character block at a time.
To facilitate stream processing, Java-language streams are encapsulated in java. io packages. To use a stream, you must import the java. io package.
Java I/O streams are based on four abstract classes: InputStream, OutputStream, Reader, and Writer. the InputStream class and its subclass can be used to input and process byte stream data; The OutputStream class and its subclass can be used to output and process byte stream data; the Reader class and its subclass can be used to input and process the streaming data. The Writer class and its subclass can be used to output and process the streaming data.
I,FileClass
The read and write operations on files in Java can be implemented through the input and output streams. However, Java provides a special File class for File directories, attributes, and management information.
(1) Construction Method of the File class
The following methods are used to create a File object:
File (String pathname); // create a path based on the path name.
File (File parent, String child); // create a File under the specified File object.
File (String parent, String child); // It is created in the specified path.
File (URL url); // creates a URL based on a URL link.
(2) common methods of File class
Boolean canRead (): determines whether the path of the File object is readable.
Boolean canWrite (): determines whether the path of the File object can be written.
Boolean exists (): determines whether the path of the File object exists.
String getAbsolutePath (): gets the absolute path of the File object.
String getParent (): gets the directory of the corresponding path of the File object.
String getPath (): obtains the path corresponding to the File object.
Boolean isAbsolute (): determines whether the path of the File object is an absolute path.
String getName (): Get the File name of the corresponding path of the File object.
Boolean isDirectory (): determines whether the path of the File object is a directory.
Boolean isFile (): determines whether the path of 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 object.
Long lastModified (): gets the last modification time of the File corresponding to the File object.
Boolean renameTo (File dest): Change the File name corresponding to the File object.
Boolean setReadOnly (): Set the File object to read-only.
(3) create a file
Create a new file by creating a file output stream. You cannot create a directory in this way. If the file to be created already exists, a new file overwrites the original file.
FileOutrputStream file = new FileOutputStream ("filename ");
(4) obtain the file list
You can use the list () or listFiles () method of the File class to obtain the list of files in a folder. The following methods are available:
String [] list ();
File [] listFiles ();
File [] listFiles (FilenameFilter filter );
File [] listFiles (FileFilter filter );
Both FileFilter and FilenameFilter are interfaces. filters are the corresponding filters. When a class is declared and the filter interface is implemented, all files that meet the filter conditions can be listed.
II,InputStreamClass andOutputStreamClass
Byte stream classes are a series of classes derived from the abstract classes InputStream and OutputStream. this type of stream uses byte as the basic processing unit. inputStream and OutputStream can be used not only to process binary data, but also to process text files.
1. Common InputStream Methods
The InputStream class is the parent class of all input streams. All methods of this class throw an IOException when an error occurs. The main methods include:
(1) public abstract int read () thows IOException
Returns an integer or-1 between 0 and 255.-1 indicates that the stream ends and other bytes are read.
(2) public int read (byte [] B) thows IOException
The method reads bytes into the byte array specified by the parameter. The returned value is the number of bytes actually read or-1 (when the stream ends ).
(3) public int read (byte [] B, int I, int B) thows IOException
The last two parameters of the method respectively indicate the start position for reading and the maximum number of bytes for reading.
(4) public int available ()
Returns the number of bytes not read in the current stream object, that is, the length of the data in the stream.
(5) public long skip (long n)
N bytes in the current stream object are skipped, and the number of bytes actually skipped is returned in the return value.
(6) public boolean markSupported ()
Determine whether the stream supports marking. Marking can easily return to the original 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 reading from this position in the future.
(9) public void reset ()
Returns the stream read position to the set mark position.
2. Common Methods of the OutputStream class
The OutputStream class is the parent class of all output streams. All methods of this class return void, and an IOException is thrown in case of an error. The main methods include:
(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 sequence.
(3) public void wirte (byte [] B, int I, int n)
Starts from the beginning of the subscript (including) in the array, the subsequent length of data is written to the stream object in turn.
(4) public void close ()
Close the current stream object and release the resources occupied by the stream object.
(5) public void flush ()
This method is used to forcibly output the buffer data in the current stream object.
Most of the methods of the above two classes are covered by the subclass of InputStream and OutputStream, except for the mark () and reset () methods.
3. FileInputStream class
The FileInputStream class is a subclass of InputStream. It can be used to process data streams that use files as data input sources to read files.
Its constructor methods include:
(1) FileInputStream (File f)
Create a file input stream using 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, IOException will be thrown, but if the directory does not exist, it will throw: FileNotFoundException.
(2) FileInputStream (String name)
Create a file input stream using a file named name as the data source.
(3) FileInputStream (FileDescriptor f)
Creates a file input stream for the input end based on the file descriptor object f.
Its main method is to overwrite 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. It is used to process data streams output from files and write data to files. Its construction methods include:
FileOutputStream (File f );
FileOutputStream (File f, boolean B );
FileOutputStream (String f );
Its main methods include: write (int B), write (byte [] B), write (byte [] B), write (byte [] B, int off, int len), close (), flush ().
5. DataInputStream and DataOutputStream
Objects Created by the DateInputStream and DataOutputStream classes are called data input streams and data output streams respectively. They implement the DataInput interface and DataOutput interface respectively. The DateInputStream class and DataOutputStream object allow reading various types of Java data.
These two streams are filter streams. They are often input or output using other streams such as InputStream or OutputStream. For example:
FileInputStream FCM = new FileInputStream ("d: \ a.txt ");
DataInputStream dis = new DataInputStream (ISI );
FileOutputStream fos = new FileOutputStream ("d: \ a.txt ");
DataOutputStream dos = new DataOutputStream (fos );
Input and Output of DateInputStream and DataOutputStream are almost the same. Read and Write methods of each basic data type can be identified by their suffix names. For example:
ReadInt (), writeInt () // read and write an int Value
ReadBoolean (), writeBoolean () // read and write a Boolean Value
ReadChar (), writeChar () // read and write a single 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 without directly reading the string
III,ReaderClass andWriterClass
The characters in Java use Unicode encoding. Each character occupies two bytes, namely, 16bit. the Bytes stream reads and writes text data based on the basic unit of processing characters represented by a 16-bit Unicode code, conversion between internal formats and external formats such as text files, display output, and keyboard input in Java programs. this method is especially suitable for Chinese Character operations. if Chinese characters are operated in bytes, garbled characters may be output.
Reader and Writer are java. the abstract parent class of all the worker streams in the io package defines the key methods for implementing other stream classes. two of the most important are read () and write (), which respectively read and write character data. the Reader and Writer classes and their subclass methods are very similar to the InputStream and OutputStream classes and their subclass usage methods. except that the parameters are replaced by character or character array.
1. Common Methods of Reader and Writer classes
The Reader class is an abstract class. All methods of this class throw an IOException in case of an error. 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 the stream supports the mark/reset method, true is returned.
(4) int read (): read a single character.
(5) int read (char [] buf): read characters into character arrays.
(6) abstract int read (char [] buf, int offset, int numChars): reads characters into a part of the array.
(7) boolean ready (): If the next input request does not have to wait, true is returned; otherwise, false is returned.
(8) void reset (): resets the input pointer to the flag set above.
(9) long skip (long numChars): Skips n characters and returns the number of characters actually skipped.
The Writer class is also an abstract class. The common methods are as follows:
(1) abstract void close (): close the output stream.
(2) abstract void flush (): determines the output status to clear any cache.
(3) void write (int ch): write a single character.
(4) void write (char [] buf): write 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, while the InputStreamReader class inherits from the Reader class. Therefore, the methods provided by the Reader class and InputStreamReader class can be used by the objects created by the FileReader class. the construction methods of FileReader include:
FileReader (File file );
FileReader (FileDescriptor e );
FileReader (String filename );
3. FileWriter class
The FileWriter class inherits from the OutputStreamWriter class, while the OutputStreamWriter class inherits from the Writer class. Therefore, the methods provided by the Writer class and OutputStreamWriter class can be used by the objects created by the FileWriter class. the FileWriter construction methods include:
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. The BufferedReader class is used to read data in the buffer. the BufferedReader class is a filtering stream. It usually uses other streams such as FileReader as their input or output. its constructor methods include:
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 each 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. the process of using the BufferedWriter class is similar to that of using BufferedReader. the difference is that the data in the buffer must be cleared using the flush () method, that is, all the data in the buffer must be written to the file. its constructor methods include:
BufferedWriter (Writer out );
BufferedWriter (Writer out, int bufSize );
IV,RandomAccessFileClass
The random file access in Java requires the RandomAccessFile class (which allows access from any location, not only reading, but also writing). It inherits directly from the Object class and implements interfaces DataInput and DataOutput.
Because the RandomAccessFile class implements all the methods defined in the DataInput and DataOutput interfaces, it can read basic types of data from files and write basic types of data to files. in addition to the methods defined in the DataInput and DataOutput interfaces, the RandomAccessFile class also defines 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 of the input stream class nor a subclass of the OutputStram class of the output stream class. however, the stream created by the RandomAccessFile class can be either the source or the destination. In other words, when performing read/write operations on a file, you can create a RandomAccessFile stream pointing to the file, in this way, the data of this file can be read from this stream, and data can be written to this file through this stream.
Two construction methods of the RandomAccessFile class:
(1) RandomAccessFile (String name, String mode)
The parameter name is used to determine a file name. The source (also the stream destination) of the created stream is provided. The parameter mode is r (read-only) or rw (read/write ), decides the access right of the created stream to the file.
(2) RandomAccessFile (File file, String mode)
The parameter file is a File object that provides the source (also the stream destination) of the created stream. The parameter mode is r (read-only) or rw (read/write ), decides the access right of the created stream to the file. when creating an object, the FileNotFoundException exception should be caught; when the stream performs read/write operations, the IOException should be caught.
The method of reading and writing information of the object RandomAccessFile is the same as that of the data input and output object. It can be all the read () and write () methods in DataInputStream and DataOutputStream.
To move a file read/write pointer:
(1) long getFilePointer (): returns the current position of the object pointer.
(2) void seek (long pos): place the file pointer in the specified absolute position. the position value is calculated based on the byte offset pos at the beginning of the file. pos 0 indicates the start of the file.
(3) long length (): the length of the returned object. The position value is length (), which indicates the end of the object.