java-input/output stream

Source: Internet
Author: User

java-input/output stream

1 , input and output:

Input/output (Input/output) refers to the input or output of data to a device or environment. Any language has the function of input and output, in the Java program, through the stream to complete the input and output, it through the Java input and output system to connect to the physical device, although the input and output stream is connected to the actual physical device is not the same, but can work in the same way. For example, the input and output of the hard disk, the network host input and output, so the device or the environment will have a variety of input and output problems and solutions.

2 , Flow:

A stream is a sequence of data that moves between the input and output of a computer. The data in a stream sequence can be either unprocessed raw binary data or a specific data that conforms to a certain format after a certain encoding is processed. The parts that are customarily called code-related are internal, and the parts that are called code-independent are external.

The stream can be divided into input stream and output stream from the way of data transmission, and the stream can be divided into byte stream and character stream from the content of the stream.

(1) input/ output stream

The purpose of the input stream is to read the data externally from within the program.

The purpose of the output stream is to write data internally from outside the program.

(2) byte stream and character stream

A byte stream (byte stream) reads and writes data in bytes, either byte-by-byte reading or writing, or a byte-block of any length (that is, a byte array).

The character stream (character stream) is written in characters, one character at a time, or a block of characters at a time while reading and writing the data in the stream.

To facilitate flow processing, the Java language flow is encapsulated in the java.io package, so you must import the Java.io package to use the stream.

Java's I/O flow is based on four abstract classes, namely InputStream, OutputStream, reader, and writer. The InputStream class and its subclasses can be used to implement input processing of byte stream data, and the OutputStream class and its subclasses can be used to implement output processing of byte stream data; the reader class and its subclasses can be used to implement input processing of character stream data The writer class and its subclasses can be used to implement output processing of character stream data.

First, File class

The read and write operations of files in Java can be implemented by input and output streams, but for information such as file directories, properties, and Management, Java provides a specialized file class.

(1) How to construct the file class

The construction method for creating a File class object is:

File (String pathname); Created by path name.

File (file parent, String child); Created under the given file object.

File (string parent, string child); Created under the specified path.

File (URL url); Created 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 file object's corresponding path.

String getParent (): Gets the directory of the file object's corresponding path.

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 file object's corresponding path.

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 files.

Boolean Ishidden (): Determines whether the file object corresponds to a hidden property.

Long Length (): Gets the length of the file object's corresponding files.

Long LastModified (): Gets the last modified time of the file object's corresponding files.

Boolean Renameto (File dest): Changes the file name of the files object.

Boolean setreadonly (): Sets the file object corresponding to read-only.

(3) Create a file

Create a new file by creating a file output stream. You cannot create a directory this way, and if the file you are creating already exists, a new file will overwrite the original file.

Fileoutrputstream file = new FileOutputStream ("filename");

(4) Get a list of files

A list of files for a folder is obtained 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);

Of these, FileFilter and FilenameFilter are both interfaces, filter for the corresponding filters. Declaring a class, implementing a filter interface, allows you to list all compliant files by filtering the criteria.

Second, InputStream Classes and OutputStream class

The byte stream class is a series of classes derived from abstract classes InputStream and OutputStream. This type of flow is in bytes as the basic processing unit. The InputStream and OutputStream classes can also be used to process text files in addition to data that can be used to process binary files.

1. Common methods of InputStream class

The InputStream class is the parent class for all input streams, and all methods of that class throw IOException when an error occurs, the main methods are:

(1) public abstract int Read () thows IOException

The method returns an integer between 0 and 255 or-1, 1 represents the end of the stream, and other bytes that correspond to the read-in.

(2) public int read (BYTE[]B) thows IOException

Method reads bytes into the byte array given by the parameter, 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) Thows IOException

The following two parameters of the method give the starting position of the read-in and the maximum number of bytes to read in each.

(4) public int available ()

Returns the number of bytes in the current stream object that have not yet been read. That is to get the length of the data in the stream.

(5) Public long skip (long N)

Skips the n bytes in the current stream object, and the number of bytes actually skipped is returned as a return value.

(6) Public boolean marksupported ()

To determine if the flow supports mark (Mark), the tag can be conveniently returned to the previously read position.

(7) public void Close ()

Closes the current stream object and frees the resource occupied by the stream object.

(8) public void mark (int i)

Sets the flag for the current position in the stream so that it can continue reading from that location at a later time.

(9) public void Reset ()

The position where the stream is read back to the setting marker.

2. Common methods of OutputStream class

The OutputStream class is the parent class for all output streams, all of which return void and, in the case of an error, throw IOException, the main methods are:

(1) public void write (int b) throws IOException

Writes a single byte of data to the end of the stream.

(2) public void write (byte[] b) throws IOException

Writes the data in array B to the current stream object, in turn.

(3) public void Wirte (byte[]b, int i, int n)

The data in the array from the beginning of the subscript (including), followed by the length, is written sequentially to the stream object.

(4) public void Close ()

Closes the current stream object and frees the resource occupied by the stream object.

(5) public void Flush ()

Forces the output of buffered data from the current stream object. Use this method to implement an immediate output.

Most methods of the above two classes are covered by subclasses of InputStream and OutputStream, except for the mark () and Reset () methods.

3, FileInputStream class

The FileInputStream class is a subclass of InputStream that can be used to process data streams that take files as data input sources, and to implement read operations on files.

It is constructed in the following ways:

(1) FileInputStream (File f)

Creates a file input stream for the data source with file object F with the specified name.

If f exists, but it should be a file path, if it is a directory will throw IOException, but if this directory does not exist, it will be thrown: FileNotFoundException.

(2) FileInputStream (String name)

Creates a file input stream for the data source with a file named name.

(3) FileInputStream (FileDescriptor f)

Establishes a file input stream for the input based on the file descriptor object F.

Its main method is to override the parent class (InputStream Class) method: 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 that are output as data and to write operations on files. It is constructed in the following ways:

FileOutputStream (File f);

FileOutputStream (File F, Boolean B);

FileOutputStream (String f);

Its main methods are methods that override the parent class: write (int b), write (Byte[]b), write (Byte[]b,int off,int len), close (), flush ().

5, DataInputStream and DataOutputStream class

The objects created by the 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 Java's various types of data.

These two streams belong to the filter stream, often with other flows such as InputStream or outputstream 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 inputs and outputs of the dateinputstream and DataOutputStream are almost corresponding, and the reading and writing methods for each basic data type can be identified from the suffix. 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 no way to read the string directly

Third, Reader Classes and Writer class

Characters in Java use Unicode encoding, with each character occupying two bytes, or 16bit. Character Stream is a 16-bit Unicode code for the basic processing unit, the text data read and write, you can implement the Java program in the internal format and text files, display output, keyboard input and other external formats between the conversion. This method is especially suitable for the operation of Chinese characters. If the Chinese character is manipulated in bytes, it is possible to output garbled characters.

Reader and writer are abstract parents of all character streams in the Java.io package, and define the key methods for implementing other flow classes. The two most important are read () and write (), which perform the reading and writing of character data respectively. Reader and writer classes and their subclasses are very similar to the methods used by the InputStream class and the OutputStream class and their subclasses. Only the arguments are replaced by characters or character arrays.

1. Common methods of reader class and writer class

The reader class is an abstract class in which all methods of the class throw IOException exceptions under the wrong conditions. Common methods are as follows:

(1) abstract void Close (): Closes the input source.

(2) void mark (int numChars): Place a marker to the current point of the input source.

(3) Boolean marksupported (): Returns true if this stream supports the Mark/reset method.

(4) int read (): reads a single character.

(5) int read (char[] buf): Read characters are read into the character array.

(6) Abstract int read (char[] buf, int offset, int numChars): reads a character into a part of the array.

(7) Boolean Ready (): Returns True if the next input request does not have to wait, otherwise false is returned.

(8) void Reset (): Resets the input pointer to the previous set of markers.

(9) long numChars: skips n characters and returns the number of characters actually skipped.

The writer class is also an abstract class, commonly used in the following ways:

(1) abstract void Close (): closes the output stream.

(2) abstract void Flush (): Determines the output state to empty any cache.

(3) void write (int ch): writes a single character.

(4) void write (char[] buf): Writes a character array.

(5) abstract void write (char[] buf, int offset, int numChars): writes part of the character array.

(6) void write (String str): Writes a string.

(7) void write (string str, int offset, int numChars): Writes part of a string.

2, FileReader class

The FileReader class inherits from the InputStreamReader class, and the InputStreamReader class inherits from the reader class. Thus the methods provided by the reader class and the InputStreamReader class are available to the objects created by the FileReader class. FileReader are constructed by:

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, Thus the methods provided by the writer class and the OutputStreamWriter class are available for use by the object created by the FileWriter class. FileWriter are constructed by:

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, and the BufferedReader class is used to read the data in the buffer. The BufferedReader class belongs to the filter stream, often with other flows such as filereader as their input or output. It is constructed in the following ways:

BufferedReader (Reader in);

BufferedReader (Reader in, int bufSize);

For example:

FileReader fr=new FileReader ("D:\1.txt");

BufferedReader buf = new BufferedReader (FR);

BufferedReader provides a 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 to the buffer. Using the BufferedWriter class is similar to using the BufferedReader class procedure. The difference is that the data in the buffer must finally be emptied with the flush () method, which means that the data in the buffer is all written to the file. It is constructed in the following ways:

BufferedWriter (Writer out);

BufferedWriter (Writer out, int bufSize);

Four, Randomaccessfile class

Random file Access in Java requires the Randomaccessfile class (which allows access from anywhere, not only read, but also write), 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 is able to read basic types of data from the file, and it can write basic types of data to the file. In addition to the methods defined in the Datainput and DataOutput interfaces, the Randomaccessfile class defines additional methods to support random access.

The Randomaccessfile class creates a stream different from the preceding input and output streams, and the Randomaccessfile class is neither a subclass of the input stream class InputStream class nor a subclass stream of the output stream class Outputstram class. However, the Randomaccessfile class creates a pointer to a stream that can be either a source or a destination, in other words, when reading and writing a file, you can create a randomaccessfile stream that points to the file. This allows you to read the file data from this stream and write the data to the file through this stream.

Two construction methods for the Randomaccessfile class:

(1) Randomaccessfile (string name, string mode)

The parameter name is used to determine a file name, give the source of the stream being created (also the stream destination), the parameter mode takes R (read-only) or RW (read-write), and determines the access rights of the created stream to the file.

(2) Randomaccessfile (file file, String mode)

The parameter file is a file object that gives the source of the created stream (which is also the stream destination), the parameter mode takes R (read-only) or RW (read-write), and determines the access rights to the file created by the stream. The filenotfoundexception exception should be caught when the object is created, and the IOException exception should be caught when the stream reads and writes.

The object Randomaccessfile read and write information in the same way as the data input and output object, and it can access all read (), write () methods in the class DataInputStream and DataOutputStream.

To move a file read and write pointers:

(1) long Getfilepointer (): Returns the current position of the file pointer.

(2) Void Seek (Long pos): Places the file pointer at the specified absolute position. The position value is calculated from the byte offset pos at the beginning of the file, and POS 0 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.

java-input/output stream

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.