IO System in Java

Source: Internet
Author: User

Java. io provides a comprehensive IO Interface, including file read/write and standard device output. In Java, IO is input and output based on a stream. All data is serialized into the output stream or read from the input stream. In specific use, many beginners are very vague about the use of Java. io packages. This article will detail the use of Java. io.

1. stream

It represents any data source capable of producing data or any receiving source capable of receiving data. In Java I/O systems, all streams (including Input and Out stream) have two types:

1.1 byte-oriented stream

A byte-oriented stream that reads or writes information to a stream in bytes. Byte-oriented streams include the following types:

Input

Stream:

1) ByteArrayInputStream: uses a buffer in the memory as an InputStream.

2) StringBufferInputStream: Use a String object as InputStream.

3) FileInputStream: uses a file as InputStream to read the file.

4) PipedInputStream: implements the pipe concept and is mainly used in the process.

5) SequenceInputStream: combines multiple inputstreams into one InputStream.

Out

Stream

1) ByteArrayOutputStream: stores information in a buffer zone in the memory.

2) FileOutputStream: stores information in a file.

3) PipedOutputStream: implements the concept of pipe, which is mainly used in the process.

4) SequenceOutputStream: combines multiple outstreams into one OutStream.

1.2 Unicode Character-oriented stream

A Unicode-oriented stream that reads or writes information from a stream in units of Unicode characters. Unicode-oriented streams include the following types:

Input

Stream

1) CharArrayReader: corresponds to ByteArrayInputStream

2) StringReader: corresponds to StringBufferInputStream

3) FileReader: corresponds to FileInputStream

4) PipedReader: corresponds to PipedInputStream.

Out

Stream

1) CharArrayWrite: corresponds to ByteArrayOutputStream

2) StringWrite: no corresponding byte-oriented stream

3) FileWrite: corresponds to FileOutputStream

4) PipedWrite: corresponds to PipedOutputStream

Character-oriented stream basically has the same functions as the corresponding byte-oriented stream. The functions of the two corresponding classes are the same, and the words are different in the operation. For example, CharArrayReader and ByteArrayInputStream both use a buffer in the memory as InputStream. The difference is that the former reads a byte of information from the memory each time, the latter reads one character from the memory each time.

1.3 conversions between two non-existing stream types

InputStreamReader and OutputStreamReader: converts a byte-oriented stream into a character-oriented stream.

2. Add attributes to stream

2.1 "adding attributes for stream"

Using the I/O APIs in Java described above, we can complete any operation we want to complete. However, through the sub-classes of FilterInputStream and FilterOutStream, we can add attributes for stream. The following is an example to illustrate the role of this function.

If we want to write data to a file, we can do this:

FileOutStream fs = new FileOutStream ("test.txt ");

Then, you can use write(writable writable) to write data to the test.txt file. However, if we want to implement the "First cache the data to be written into the file into the memory, then write the data in the cache into the file" function, none of the above APIs can meet our needs. However, we can use the sub-classes of FilterInputStream and FilterOutStream to add the required functions for FileOutStream.

2.2FilterInputStream types

2.2.1 encapsulate byte-oriented InputStream

1) DataInputStream: reads data of basic types (such as int and char) from stream.

2) BufferedInputStream: Buffer

3) LineNumberInputStream: records the number of rows in the input stream. You can call getLineNumber () and setLineNumber (int)

4) PushbackInputStream: rarely used and generally used for Compiler Development

2.2.2 encapsulate character-oriented InputStream

1) there is no class corresponding to DataInputStream. Unless you use BufferedReader when using readLine (), use DataInputStream

2) BufferedReader: corresponds to BufferedInputStream

3) LineNumberReader: corresponds to LineNumberInputStream

4) PushBackReader: corresponds to PushbackInputStream

2.3FilterOutStream types

2.2.3 encapsulate byte-oriented OutputStream

1) DataIOutStream: outputs basic data types (such as int and char) to stream.

2) BufferedOutStream: Buffer

3) PrintStream: produce formatted output

2.2.4 character-oriented OutputStream Encapsulation

1) BufferedWrite: corresponds

2) PrintWrite: corresponds

3. RandomAccessFile

1) You can use the RandomAccessFile object to read and write files.

2) when an object is generated, you can specify the nature of the file to be opened: r, read-only; w, write-only; rw, read/write

3) You can directly jump to the specified position in the file.

3. An example of an I/O Application

Java code

Import java. io .*;

Public class TestIO {

Public static void main (String [] args)

Throws IOException {

// 1. read data from a file in behavior units

BufferedReader in = new BufferedReader (

New FileReader ("F: nepalonTestIO. java "));

String s, s2 = new String ();

While (s = in. readLine ())! = Null)

S2 + = s + "n"; in. close ();

// 1b. Receive keyboard input

BufferedReader stdin = new BufferedReader (new InputStreamReader (System. in ));

System. out. println ("Enter a line :");

System. out. println (stdin. readLine ());

// 2. read data from a String object

StringReader in2 = new StringReader (s2 );

Int c;

While (c = in2.read ())! =-1)

System. out. println (char) c );

In2.close ();

// 3. Extract formatted input from memory

Try {DataInputStream in3 = new DataInputStream (new ByteArrayInputStream (s2.getBytes ()));

While (true)

System. out. println (char) in3.readByte ());

}

Catch (EOFException e) {System. out. println ("End of stream ");

} // 4. output to the file try {BufferedReader in4 = new BufferedReader (new StringReader (s2 ));

PrintWriter out1 = new PrintWriter (new BufferedWriter (new FileWriter ("F: nepalon TestIO. out ")));

Int lineCount = 1;

While (s = in4.readLine ())! = Null)

Out1.println (lineCount ++ ":" + s );

Out1.close ();

In4.close ();

}

Catch (EOFException ex) {System. out. println ("End of stream ");

}

// 5. Data Storage and Restoration

Try {DataOutputStream out2 = new DataOutputStream (new BufferedOutputStream (

New FileOutputStream ("F: nepalon Data.txt ")));

Out2 writedouble (3.1415926 );

Out2.writeChars ("nThas was pi: writeCharsn ");

Out2.writeBytes ("Thas was pi: writeByten ");

Out2.close ();

DataInputStream in5 = new DataInputStream (

New BufferedInputStream (new FileInputStream ("F: nepalon Data.txt ")));

BufferedReader in5br = new BufferedReader (new InputStreamReader (in5 ));

System. out. println (in5.readDouble ());

System. out. println (in5br. readLine ());

System. out. println (in5br. readLine ());

}

Catch (EOFException e ){

System. out. println ("End of stream ");

}

// 6. Operate the file through RandomAccessFile

RandomAccessFile rf = new RandomAccessFile ("F: nepalon rtest. dat",>

For (int I = 0; I <10; I ++)

Rf. writeDouble (I * 1.414 );

Rf. close ();

Rf = new RandomAccessFile ("F: nepalon rtest. dat",>

For (int I = 0; I <10; I ++)

System. out. println ("Value" + I + ":" + rf. readDouble ());

Rf. close ();

Rf = new RandomAccessFile ("F: nepalon rtest. dat",>

Rf. seek (5*8 );

Rf. writeDouble (47.0001 );

Rf. close ();

Rf = new RandomAccessFile ("F: nepalon rtest. dat",>

For (int I = 0; I <10; I ++)

System. out. println ("Value" + I + ":" + rf. readDouble ());

Rf. close ();

}

}

Code explanation (in the unit of Zone ):

In Area 1, when reading a file, first read the file content to the cache, when calling in. readLine (), and then read data from the cache in character format (hereinafter referred to as "cache byte read mode ").

In section 1b, to read data from the standard I/O (keyboard) as a cache byte, you must first set the standard I/O (System. in) is converted to a character-oriented stream and then encapsulated by BufferedReader.

In area 2, a StringReader stream is generated to read data from a String object in the form of characters.

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.