Java JDK 6 learning notes stream

Source: Internet
Author: User

 

Http://book.51cto.com/art/200812/101093.htm

 

14.2-bit stream

Data in the computer is stored in the form of 0 and 1. If you want to access data between two devices, it is also in the form of 0 and 1, java abstracts the flow of data between the destination and source into a stream, while the flow in the stream is BIT data.

14.2.1 inputstream and outputstream

In the computer, the data flows through the circuit, while the above flows through the current, the current potential has a low and high, that is, the number of 0 and 1. From the program's point of view, data flows between data destinations (such as memory) and sources (such as files) are usually abstracted into a stream ), the flow is BIT data, as shown in 14-1.

 

 

There are two classes in Java SE used for stream Abstraction: Java. Io. inputstream and Java. Io. outputstream.

Inputstream is the parent class of all classes that represent bit input streams. It is an abstract class and its subclass must be redefined to define the abstract method defined in it. Inputstream is an abstract representation of the data read from the device source. For example, the in object of the standard input stream in system is an inputstream instance. After the Java program starts, the in Stream object is enabled to read data from the standard input device, which is usually a keyboard or user-defined input device.

Outputstream is the parent class of all classes that indicate bit output streams. It is an abstract class. The subclass must redefine the defined abstract method. outputstream is an abstract representation used to write data to the destination. For example, the out type of the standard output stream object in system is Java. Io. printstream. This class is a subclass of outputstream (Java. Io. filteroutputstream inherits outputstream, and printstream inherits filteroutputstream ). After the program starts, the out flow object is enabled and data can be written to the destination device through out. This device is usually a screen display or user-defined output device.

Example 14.4 can read the keyboard input stream. The read () method of the in object reads one byte of data at a time, and the data read is returned as int type. Therefore, when the out object is used to display the data, it is in decimal mode.

Example 14.4 streamdemo. Java

Package onlyfun. Caterpillar;

Import java. Io .*;

Public class streamdemo {
Public static void main (string [] ARGs ){
Try {
System. Out. Print ("input character :");
System. Out. println ("input character in decimal format:" +
System. In. Read ());
}
Catch (ioexception e ){
E. printstacktrace ();
}
}
}

Execution result:

Input character:
Input character in decimal format: 65

After character a is input, it is read by the standard input stream in. The bit of a indicates that it is 65 in decimal format. This is the encoding of Character A (see the ASCII coding table ).

Generally, methods on inputstream or outputstream are rarely directly implemented, because these methods are relatively low-level and generally implement their subclasses. The methods defined on these subclasses are more convenient for input/output.

 

 

 

14.2.2 fileinputstream and fileoutputstream

Java. Io. fileinputstream is a subclass of inputstream. You can see from the file name at the beginning that fileinputstream is related to reading data from the specified file to the destination. Java. Io. fileoutputstream is a subclass of outputstream. As the name suggests, fileoutputstream is mainly related to writing data from the source to the specified file.

When you create a fileinputstream or fileoutputstream instance, you must specify the file location and file name. When the instance is created, the file stream is enabled. If you do not use a stream, you must disable the file stream, to release system resources that are dependent on the stream and complete file read/write operations.

Fileinputstream can use the read () method to read one byte at a time and return it as an int type, or read it into a byte array using the read () method. The number of elements in the byte array, the number of bytes read. In the process of reading or writing the entire file, such a byte array is usually treated as a buffer, because such a byte array usually plays an intermediate role to undertake data.

Example 14.5 is an example of using fileinputstream and fileoutputstream. The program can copy a file, which reads data from the source file to a byte array first, and then writes the data from the byte array to the target file.

Example 14.5 filestreamdemo. Java

package onlyfun.caterpillar;
import java.io.*;
public class FileStreamDemo {
public static void main(String[] args) {
try {
byte[] buffer = new byte[1024];

 

// Source file
Fileinputstream =
New fileinputstream (new file (ARGs [0]);
// Target file
Fileoutputstream =
New fileoutputstream (new file (ARGs [1]);

 

// Available () can obtain the length of unread data
System. Out. println ("copy file:" +
Fileinputstream. Available () + "Byte ");

 

While (true ){
If (fileinputstream. Available () <1024 ){
// The remaining data is less than 1024 bytes
// Read and write data to the target file
Int remain =-1;
While (remain = fileinputstream. Read ())
! =-1 ){
Fileoutputstream. Write (remain );
}
Break;
}
Else {
// Read data from the source file to the buffer
Fileinputstream. Read (buffer );
// Write the array data to the destination file
Fileoutputstream. Write (buffer );
}
}

 

// Close the stream
Fileinputstream. Close ();
Fileoutputstream. Close ();

 

System. Out. println ("copied ");
}
Catch (arrayindexoutofboundsexception e ){
System. Out. println (
"Using: Java filestreamdemo SRC des ");
E. printstacktrace ();
}
Catch (ioexception e ){
E. printstacktrace ();
}
}
}

The program demonstrates two read () methods. One method can read data of the specified length to an array, and the other method can read one byte at a time. After each read, the cursor is directed forward. If no data is read,-1 is returned. The available () method is used to obtain the number of bytes that can be read. In addition to using file to create fileinputstream and fileoutputstream instances, you can also directly use a string to specify a path.

// Source file
Fileinputstream =
New fileinputstream (ARGs [0]);
// Target file
Fileoutputstream =
New fileoutputstream (ARGs [1]);

When you do not use a file stream, remember to close the stream by using the close () method to release system resources that are dependent on the stream. Example: Copy filedemo.javato filedemo.txt:

Java onlyfun. Caterpillar. filestreamdemo filedemo. Java filedemo.txt
Copy file: 1723 bytes
Copied

By default, fileoutputstream starts the stream by creating a new file. If the specified file name already exists, the original file will be overwritten. If you want to write the file in the additional mode, you can specify the additional mode when building the fileoutputstream instance. For example:

FileOutputStream fileOutputStream =
new FileOutputStream(args[1], true);

If the second append parameter of the build method is set to true, a new file is created if the file does not exist when the stream is enabled. If the file exists, the stream is directly enabled, and append the written data to the end of the file.

 

 

 

14.2.3 bufferedinputstream and bufferedoutputstream

In the case of fileinputstream and fileoutputstream, a byte array is used as the buffer for Data Reading. in the case of file access, the hard disk access speed is much lower than the data access speed in the memory. To reduce access to the hard disk, data of a certain length is usually read from the file at a time, and data of a certain length is written at the time of writing, which can increase the efficiency of file access.

Java. Io. bufferedinputstream and Java. Io. bufferedoutputstream can add the buffer function for inputstream and outputstream objects. When constructing a bufferedinputstream instance, you must specify an inputstream instance. When bufferedinputstream is implemented, the inputstream instance is actually implemented. Similarly, when constructing a bufferedoutputstream, you also need to specify an outputstream instance to implement an outputstream instance.

The data member Buf of bufferedinputstream is a single-digit group. The default value is 2048 bytes. When reading data sources, such as files, bufferedinputstream will try to fill up the Buf. When the read () method is used, the data in the Buf is read first, rather than directly reading the data source. When the data in the Buf is insufficient, bufferedinputstream will implement the read () method of the given inputstream object to extract data from the specified device, as shown in Figure 14-2.

 

 

 

The data member Buf of bufferedoutputstream is a single-digit group. The default value is 512 bytes. When data is written using the write () method, the data is actually written to the Buf first. When the Buf is full, the write () method of the given outputstream object is implemented, write the Buf data to the destination, instead of writing the data to the destination every time.

The following describes how to rewrite example 14.5. Instead of setting the buffer, bufferedinputstream and bufferedoutputstream make the program simpler and more efficient.

Example 14.6 bufferedstreamdemo. Java

package onlyfun.caterpillar;

import java.io.*;

public class BufferedStreamDemo {
public static void main(String[] args) {
try {
byte[] data = new byte[1];

 

File srcfile = new file (ARGs [0]);
File desfile = new file (ARGs [1]);

 

Bufferedinputstream =
New bufferedinputstream (
New fileinputstream (srcfile ));
Bufferedoutputstream =
New bufferedoutputstream (
New fileoutputstream (desfile ));

System. Out. println ("copy file:" +
Srcfile. Length () + "Byte ");

 

While (bufferedinputstream. Read (data )! =-1 ){
Bufferedoutputstream. Write (data );
}

// Write all the data in the buffer.
Bufferedoutputstream. Flush ();

// Close the stream
Bufferedinputstream. Close ();
Bufferedoutputstream. Close ();

 

System. Out. println ("copied ");
}
Catch (arrayindexoutofboundsexception e ){
System. Out. println (
"Using: Java usefilestream SRC des ");
E. printstacktrace ();
}
Catch (ioexception e ){
E. printstacktrace ();
}
}
}

To ensure that the data in the buffer zone must be written to the destination, we recommend that you execute flush () to write all the data in the buffer zone to the destination stream. The execution result of this example is the same as that of example 14.5.

Bufferedinputstream and bufferedoutputstream do not change the inputstream or outputstream behavior. The inputstream and outputstream actions are responsible for reading or writing data.Bufferedinputstream and bufferedoutputstream dynamically add some additional functions (such as the buffer function) to them before the corresponding methods are operated)Here, the object access stream is used as an example. In fact, bufferedinputstream and bufferedoutputstream can be used on other stream objects.

 

14.2.4 datainputstream and dataoutputstream

Java. Io. datainputstream and Java. Io. dataoutputstream provide some methods for writing Basic Java data types, such as reading and writing int, double, and Boolean. Because the size of Java data types is well defined, when writing or reading these basic data types, you don't have to worry about the different data sizes between different platforms.

Here we will describe it with file access. Sometimes it is only necessary to store the member data of an object, rather than the information of the entire object. The assumption of the member data type is the basic data type of Java, this requirement does not need to use stream objects related to object Input and Output. You can use datainputstream and dataoutputstream to write or read data.

The following example describes how to use datainputstream and dataoutputstream. First, design a member class.

Example 14.7 member. Java

package onlyfun.caterpillar;
public class Member {
private String name;
private int age;

 

Public Member (){
}

 

Public Member (string name, int age ){
This. Name = Name;
This. Age = age;
}

 

Public void setname (string name ){
This. Name = Name;
}

 

Public void setage (INT age ){
This. Age = age;
}

 

Public String getname (){
Return name;
}

 

Public int getage (){
Return age;
}
}

We plan to write the member data of a member instance to a file, and restore the data to a member object after reading the file data. Example 14.8 demonstrates how to implement this requirement.

Example 14.8 datastreamdemo. Java

Package onlyfun. Caterpillar;

Import java. Io .*;

Public class datastreamdemo {
Public static void main (string [] ARGs ){
Member [] members = {New Member ("Justin", 90 ),
New member ("momor", 95 ),
New member ("Bush", 88 )};
Try {
Dataoutputstream =
New dataoutputstream (
New fileoutputstream (ARGs [0]);

For (Member member: Members ){
// Write the UTF string
Dataoutputstream. writeutf (member. getname ());
// Write int data
Dataoutputstream. writeint (member. getage ());
}
// Read all data to the destination
Dataoutputstream. Flush ();
// Close the stream
Dataoutputstream. Close ();

Datainputstream =
New datainputstream (
New fileinputstream (ARGs [0]);
// Read the data and restore it to an object
For (INT I = 0; I <members. length; I ++ ){
// Read the UTF string
String name = datainputstream. readutf ();
// Read int data
Int score = datainputstream. readint ();
Members [I] = new member (name, score );
}
// Close the stream
Datainputstream. Close ();

 

// Display restored data
For (Member member: Members ){
System. Out. printf ("% S/T % d % N ",
Member. getname (), member. getage ());
}
}
Catch (ioexception e ){
E. printstacktrace ();
}
}
}

When reading data from a file, you do not have to worry about when to stop reading the string or reading the int type. Use the corresponding readutf () or readint () the method can read the complete data correctly. Similarly, datainputstream and dataoutputstream do not change the behaviors of inputstream or outputstream. The read or write operations are still the responsibility of inputstream and outputstream.Datainputstream and dataoutputstream dynamically Add the type judgment function to the corresponding methods.Although the object access stream is used as an example, the datainputstream and dataoutputstream functions can be used on other stream objects.

 

 

 

 

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.