"Java Programming Ideas Fourth Edition" notes---Chapter 18 (3) I/O streaming part--character streams byte stream __ algorithm

Source: Internet
Author: User
java.io Stream Class library

There are four basic classes in the Java.io package: InputStream, OutputStream, and reader, writer classes, which deal with byte streams and characters, respectively:



The JDK1.4 version began introducing a new I/O class library, which is located in the Java.nio package, and the new I/O class Library uses channels and buffers to improve I/O operations efficiency.

In the Java.io package, Java.io.InputStream represents the byte input stream, Java.io.OutputStream represents the byte output stream, at the top of the java.io package. These two classes are abstract, that is, they cannot be instantiated, and a subclass must be generated before certain functionality can be achieved.


two. The specific classification of IO flow

(i) Overall classification by I/O type:

1. Memory

1 read/write data from/to memory array: CharArrayReader, Chararraywriter, Bytearrayinputstream, Bytearrayoutputstream

2 From/To memory string read and write Data StringReader, StringWriter, StringBufferInputStream

2.Pipe Pipe

Implement pipeline input and output (interprocess communication): Pipedreader, PipedWriter, PipedInputStream, PipedOutputStream

3.File file Stream

Read and write to files: FileReader, FileWriter, FileInputStream, FileOutputStream

4. Objectserialization

Object input, Output: ObjectInputStream, ObjectOutputStream

5.DataConversion Data Flow

Read and write by basic data type (processed data is the basic type of Java (such as Boolean, Byte, Integer, and floating-point numbers)): DataInputStream, DataOutputStream

6.Printing

Contains convenient printing methods: PrintWriter, PrintStream

7.Buffering Buffering

When reading or writing, the data is cached to reduce the number of I/O: BufferedReader, BufferedWriter, Bufferedinputstream, Bufferedoutputstream

8.Filtering Filter Flow

Filtering when data is read or written: FilterReader, Filterwriter, FilterInputStream, Filteroutputstream

9.Concatenation Merge Input

To connect multiple input streams into one input stream: Sequenceinputstream

10.Counting Count

Count rows When reading data: LineNumberReader, Linenumberinputstream

11.Peeking ahead

Pre-read by caching mechanism: Pushbackreader, Pushbackinputstream

12. Conversion Flow

byte flow character stream: InputStreamReader, OutputStreamWriter


(ii) Classification by data source (whereabouts):

1, file (files): FileInputStream, FileOutputStream, FileReader, FileWriter

2, Byte[]:bytearrayinputstream, Bytearrayoutputstream

3, char[]: CharArrayReader, Chararraywriter

4, String:stringbufferinputstream, StringReader, StringWriter

5, network Data flow: InputStream, OutputStream, Reader, Writer
Third, byte stream Inputstream/outputstream

1. InputStream Abstract class

InputStream is a byte input stream, which itself is an abstract class that must be implemented by its subclasses, which is a superclass of all classes that represent the byte input stream. The stream that inherits from InputStream is the input data to the program, and the Data Unit is byte (8bit);

InputStream is a class for entering byte data, so the InputStream class provides 3 overloaded read methods.


Common methods in the InputStream class:

(1) public abstract int Read (): reads a byte of data, the return value is the value of the type int of the high level complement 0. If the return value =-1 description does not read to any byte read work ends.

(2) public int read (byte b[]): reads b.length bytes of data into array B. The return value is the number of bytes read. The method actually calls the next method implementation.

(3) public int read (byte b[], int off, int len): reads up to len bytes of data from the input stream, and holds it in an array B with an offset of off.

(4) public int available (): Returns the number of bytes that can be read in the input stream. Note: If the input is blocked, the current thread will be suspended, and if the InputStream object calls this method, it will only return 0, and this method must be invoked by the subclass object that inherits the InputStream class.

(5) Public long skip (long N): ignores n bytes in the input stream, the return value is the number of bytes actually ignored, skipping some bytes to read

(6) public int close (): After we use it, we must turn off the stream we open.

Main subclasses:

1) FileInputStream a file as a inputstream, to achieve the read operation of the file

2) Bytearrayinputstream: Use a buffer in memory as a InputStream

3) StringBufferInputStream: Put a String object as a InputStream

4) PipedInputStream: Realize the concept of pipe, mainly used in the thread

5) Sequenceinputstream: Combine multiple inputstream into one InputStream


2. OutputStream Abstract class

OutputStream provides 3 write methods to do the output of data, which is relative to InputStream.

1. public void Write (byte b[): Writes the bytes in parameter B to the output stream.

2. public void Write (byte b[, int off, int len): writes the Len byte from the offset off of parameter B to the output stream.

3. Public abstract void Write (int b): first converts the int to a byte type, and writes the low byte to the output stream.

4. public void Flush (): Outputs all the data in the data buffer and empties the buffer.

5. public void Close (): closes the output stream and releases the system resources associated with the stream.

Main subclasses:

1) Bytearrayoutputstream: Storing information in a buffer in memory

2) FileOutputStream: Deposit The information in the file

3) PipedOutputStream: Realize the concept of pipe, mainly used in the thread

4) Sequenceoutputstream: Combine multiple outstream into one OutStream

The judgment of the end of the stream: Method Read () Returns a value of-1 o'clock; ReadLine () returns a null value.


3. File input stream: FileInputStream class

FileInputStream can use the Read () method to read a byte at a time, return it as an int, or read it to a byte array when using the Read () method, and how many bytes the element of the byte array is enrolled in. In the process of reading or writing an entire file, such a byte array is usually treated as a buffer because such a byte array usually acts as an intermediate role in the data.

Function: A data stream that takes a file as a data input source. Or a class that opens a file, reads data from a file to memory.

Use Method (1)

File Fin=new file ("D:/abc.txt");

FileInputStream in=new FileInputStream (Fin);

Use Method (2)

FileInputStream in=new FileInputStream ("D:/abc.txt");

Program Examples:

Display the contents of a Inputfromfile.java program on the Monitor
import java.io.ioexception; import java.io.fileinputstream; public class testfile {    public static void main (String  args[])  throws ioexception {        try {             FileInputStream rf =  New fileinputstream ("Inputfromfile.java");             int n = 512;             byte buffer[] = new  byte[n];             while  (Rf.read (buffer, 0,  n)  != -1  &&  (n > 0))  {                 SYSTEM.OUT.PRINTLN (new String (buffer));             }              system.out.println ();             rf.close ();         } catch  (Ioexception ioe)  {             system.out.println (IOe.toString ());         }     }

}


4. File output stream: FileOutputStream class

Action: Used to process data streams with files as data outputs, or read data into files from memory areas

The FileOutputStream class is used to process data streams with files as data output, a string that represents a file name, or a file or FileDescriptor object.

There are two ways to create a file stream object:

Mode 1:

File F=new file ("D:/myjava/write.txt");

FileOutputStream out= New FileOutputStream (f);

Mode 2:

FileOutputStream out=new FileOutputStream ("D:/myjava/write.txt");

Mode 3: The constructor takes the FileDescriptor () object as its argument.

FileDescriptor () fd=new filedescriptor ();

FileOutputStream f2=new FileOutputStream (FD);

Mode 4: The constructor takes the file name as its first parameter and the Boolean value as the second argument.

FileOutputStream f=new FileOutputStream ("D:/abc.txt", true);

Attention:

(1) When writing the data in the file, if the file already exists, then overwrite the existing file;

(2) When the read/write operation ends, the Close method should be called to turn off the stream.

Program Example: Use the keyboard to enter a piece of article, save the article in the file Write.txt
Import java.io.IOException; Import Java.io.FileOutputStream; public class Testfile {public static void main (String args[]) throws IOException {&NB

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.