Talking about the example of input and output flow in Java _java

Source: Internet
Author: User
Tags flush readable

The input and output capabilities of the Java language are very powerful and flexible, and the drawback is that the code that looks like input and output is not very concise, because you often need to wrap many different objects. In the Java class Library, the IO part of the content is very large, because it involves a wide range of areas: standard input and output, file operations, network data flow, string flow, object flow, zip file flow .... The purpose of this article is to introduce Java input and output flow examples.

Hierarchy of Streams

  Defined:

Java reads the data object into the input stream, and the object to which it is written is called the output stream. The structure diagram is as follows:

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, is through the flow to complete the input and output, it through the Java input and output system connected to the physical device, although the input output stream 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 different equipment or environment will have a wide range of input and output problems and solutions.

2, Flow:

A stream is a sequence of data that moves between input and output of a computer. The data in a stream sequence can be either raw binary data or a specific data that is processed by a certain encoding and conforms to a certain format. It is customary to say that the part of the code is internal, and that the part that is unrelated to the code is external.

From the data transmission mode, the flow can be divided into input and output streams, from the content of the flow, streams can be divided into byte stream and character streams.

(1) input and output stream

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

The function of an output stream is to write data from outside the program to the inside.

(2) byte stream and character streams

The word stream (byte stream) reads and writes data in bytes, either read or write data from one byte to the other, or read or write to any length of byte block (that is, an array of bytes) at a time.

The character stream (character stream) is used in characters, one character at a time, or one character block at a time when reading and writing streaming data.

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

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

A, the file class

The reading and writing of files in Java can be achieved by input and output streams, but Java provides a specialized file class for the directory, attributes, and management information.

(1) The method of constructing the file class

The construction methods for creating a file class object are:

File (String pathname); Created according to the path name.

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

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

File (URL url); Created according to a URL link.

(2) Common methods of the file class

Boolean CanRead (): Determines whether the path to the file object is readable.

Boolean canwrite (): Determines whether the path to the file object is writable.

Boolean exists (): Determines whether the path 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 corresponding path to the file object.

String GetPath (): Gets the path corresponding to the file object.

Boolean Isabsolute (): Determines whether the path to the file object corresponds to an absolute path.

String getName (): Gets the file name of the corresponding path to the file object.

Boolean isdirectory (): Determines whether the path to the file object is a directory.

Boolean isfile (): Determines whether the path to the file object corresponds to files.

Boolean Ishidden (): Determines whether the file corresponding to the files object is 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): Change the filename of the file object's counterpart.

Boolean setreadonly (): Sets the file object counterpart 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, 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) Get the file list

Obtain a list of files for a 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);

Wherein, the FileFilter and the FilenameFilter are interfaces, and filter filters are the corresponding filter. Declaring a class that implements a filter interface allows you to list all eligible files by filtering the criteria.

Ii. InputStream class and OutputStream class

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

1, the common method of InputStream class

The InputStream class is the parent class for all input streams, and all methods of that class throw ioexception when errors occur, mainly by:

(1) public abstract int Read () thows IOException

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

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

Method reads the byte into the byte array given by the argument, and the return value is the number of bytes actually read or-1 (the end of the stream is encountered).

(3) public int read (byte[]b, int i, int b) Thows IOException

The latter two parameters of the method give the starting position of the read in and the maximum number of bytes read.

(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 n bytes in the current stream object, and the actual number of bytes skipped is returned as a return value.

(6) Public boolean marksupported ()

To determine whether the stream supports markup (mark), the tag can easily go back to where it was originally read.

(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 a 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 ()

Returns the location where the stream is read back to the set mark.

2, the common method of OutputStream class

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

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

Writes a 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 is then written to the stream object from the start subscript (included) and subsequent lengths.

(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 in the current stream object out. Use this method to achieve immediate output.

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

3, FileInputStream class

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

Its construction methods are:

(1) FileInputStream (File f)

Creates a file input stream for the data source with the file object F of 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 when it will throw: FileNotFoundException.

(2) FileInputStream (String name)

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

(3) FileInputStream (FileDescriptor f)

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

Its primary approach 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 file as data output, and to write to files. Its construction methods are:

FileOutputStream (File f);

FileOutputStream (File F, Boolean B);

FileOutputStream (String f);

Its main method is to overwrite 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. Dateinputstream classes and DataOutputStream objects allow you to read various types of Java data.

These two streams belong to the filter stream and are often used as input or output by other streams such as InputStream or OutputStream. 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 the same, and the read-write methods for each basic data type can be identified from the prefix name. For example:

ReadInt (), writeint ()/read an int value

Readboolean (), Writeboolean ()/Read a Boolean value

Readchar (), Writechar ()/read one 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

Third, reader class and writer class

The characters in Java Use Unicode encoding, and each character occupies two bytes, or 16bit. Character Stream is a 16-bit Unicode code as the basic processing unit of characters, read and write text data, 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 operated in byte form, it is possible to output garbled characters.

Reader and writer are abstract parent classes of all character streams in the java.io package, defining key methods for implementing other flow classes. The two most important of these are read () and write (), which read and write the character data separately. The methods of reader and writer classes and their subclasses are very similar to those used by InputStream classes and OutputStream classes and their subclasses. Only the arguments are replaced with characters or an array of characters.

1, reader class and writer class of common methods

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

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

(2) void mark (int numchars): Place a mark 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 character read to character array.

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

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

(8) void Reset (): Resets the input pointer to the previously set mark.

(9) long Skip (long numchars): Skips n-character input, returning the number of characters actually skipped.

The writer class is also an abstract class, with the following common methods:

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

(2) abstract void Flush (): Determines the output status 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): Write part of a character array.

(6) void write (String str): Write String.

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

2, FileReader class

The FileReader class is inherited from the InputStreamReader class, and the InputStreamReader class inherits from the reader class. Therefore, the methods provided by both the reader class and the InputStreamReader class are available to objects created by the FileReader class. The construction 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 objects created by the FileWriter class. The construction 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, and the BufferedReader class is used to read data in the buffer. The BufferedReader class belongs to the filter stream and is often used as input or output by other streams such as FileReader. 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 a readerline () method for reading 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. Using the BufferedWriter class is similar to using the BufferedReader class procedure. The difference is that the data in the buffer must end up with the flush () method to empty the buffer, which means that all data in the buffer is written to the file. Its construction methods are:

BufferedWriter (Writer out);

BufferedWriter (Writer out, int bufsize);

Four, Randomaccessfile class

Random file Access in Java requires the use of the Randomaccessfile class, which allows access from any location, not only to read, but also to write, directly from the object class and implement interfaces Datainput and DataOutput.

Because the Randomaccessfile class implements all of the methods defined in the Datainput and DataOutput interfaces, it is possible to read basic types of data from a file or write basic types of data to a 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 Randomaccessfile class creates a stream that is different from the preceding input and output stream, 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. But the Randomaccessfile class creates a stream that can be either a source or a destination, in other words, when reading and writing to a file, you can create a randomaccessfile stream that points to that file. This allows the data to be read from this stream and written 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 filename, give the source (also the stream destination) of the created stream, parameter mode, R (read-only), or RW (readable and writable), and determine the access rights to the file created by the stream.

(2) Randomaccessfile (file file, String mode)

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

Objects Randomaccessfile Read and write information in the same way as data input and output objects, which can access all the read () and write () methods in class DataInputStream and DataOutputStream.

How to move a file read and write pointer:

(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 computed from the byte offset pos at the beginning of the file, and the 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.

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.