Java input/output stream (1)-common input/output streams and java input/output streams

Source: Internet
Author: User

Java input/output stream (1)-common input/output streams and java input/output streams

1. Concept of stream: in Java, a stream is an ordered sequence of bytes from the source to the destination. Java has two basic streams: InputStream and OutputStream ).

The stream is divided into node stream and filter stream based on the difference between the stream and another terminal of the program.

(1) node stream: constructs an input and output stream with a specific source such as a disk file, a memory area, or a pipe between threads as the endpoint. It is a basic stream.

(2) filter stream: An input/output stream constructed with other existing streams as the endpoint.

The data units in a stream are divided into byte streams and byte streams.

(1) byte stream: Data in the stream is read and written in 8 bytes, and InputStream and OutputStream are basic classes.

(2) bytes stream: the data in the stream is read and written in units of 16 characters, and Reader and Writer are the basic classes.

2. byte stream

InputStream and OutputStream are two top-level parent classes of the byte stream. They provide common APIs for the input stream class and output stream class.

2.1 input byte stream

Basic Method of InputStream:

(1) Basic read method;: int read () int read (byte [] B) int read (byte [] B, int off, int len)

(2) close the stream: void close ()

(3) return the number of readable bytes in the input stream, int available ()

(4) skip the specified byte long skip (long n)

(5) boolean markSupported () void Mark (int readlimt) void reset ()

2.2 output streams

Basic Method of OutputStream:

(1) Basic write method: void write (int c) void write (byte [] B) void write (byte [] B, int off, int len)

(2) close the stream: void close ()

(3) q forced output: void flush ()

3. streams:

Reader and Writer are the top-level parent classes of the character stream. The character stream can process all characters in the Unicode Character Set. The member method is similar to word throttling.

3. Input/output stream Integration

Node streams are not very common in programs. Generally, multiple streams are connected by filtering streams to process data together using the features of each stream. For example, to improve efficiency, a file stream is encapsulated with a cache stream and finally a data stream.

4. Common input and output streams

4.1 file stream: The file stream belongs to the node stream, including the FileInputStream and FileOutputStream classes, as well as the Reader and Writer classes. These classes read and write files in the file system. When a File stream is created, the corresponding constructor is called, and the File name or object of a File class in string format is often used as a parameter. For example:

public FileInputStream(String name);public FileInputStream(File file);

Example: Use a file stream to copy a file.

(1) implemented through the file byte stream:

package ch07;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class CopyBytes {public static void main(String[] args) throws IOException {//create two File class object//File inputFile=new File("E:\\workspace\\tmpfile\\farrago.txt");//File outputFile=new File("E:\\workspace\\tmpfile\\outagainb.txt");//create file input/output byteStreamFileInputStream inputStream=new FileInputStream(new File("E:\\workspace\\tmpfile\\farrago.txt")); //attention:throw exceptionFileOutputStream outputStream=new FileOutputStream(new File("E:\\workspace\\tmpfile\\outagainb.txt"));int c;while((c=inputStream.read())!=-1){outputStream.write(c);System.out.println(c);}inputStream.close();outputStream.close();System.out.println("done! the file is in E:\\workspace\\tmpfile\\outagainb.txt");}}

(2) use the File Upload stream for implementation

Package ch07; import java. io. fileReader; import java. io. fileWriter; import java. io. IOException; public class Copy {public static void main (String [] args) throws IOException {// create a file character input/output stream FileReader in = new FileReader ("E: \ workspace \ tmpfile \ farrago.doc "); FileWriter out = new FileWriter (" E: \ workspace \ tmpfile \ outagainb.doc "); int c; while (c = in. read ())! =-1) {System. out. println (c); out. write (c);} in. close (); out. close ();}}

Farrago.doc is available in the specified directory at runtime, and outagainb.doc is generated in the same directory after the program runs. The content is the same as farrago.doc.

4.2 buffer stream

BufferedInputStream, BufferedOutputStream, BufferedReader, and BufferedWriter. This type of stream reads data from the original stream into blocks or writes data in batches when it accumulates a large amount of data. BufferedOutputStream and BufferedWrite write data to the destination only when the buffer is full or flush () is called.

Constructor:

public BufferedInputStream(InputStream in)public BufferedInputStream(InputStream in,int size)

4.3 MPs queue Flow

Pipeline streams can directly transmit data between threads.

(1) pipeline stream model:

PipedReader/PipedInputStream implements the input stream of the pipeline, while PipedWriter and PipedOutputStream implement the output stream.

(2) pipeline flow creation:

The pipeline flow is created to connect the input stream of the pipeline and the output stream of the pipeline. The constructor has the following two methods:

PipedInputStream pInputStream = new PipedInputStream (); pipeline pOutputStream = new pipeline (pInputStream); or PipedInputStream pInputStream = new PipedInputStream (); pipeline pOutputStream = new pipeline (); pInputStream. connect (pOutputStream); pOutputStream. connect (pInputStream );

(3) pipeline stream instance: Word processing program. Read the words from the file, sort each word in reverse order, and finally restore the output in reverse order.

RhymingWords. java: includes the main (), reverse (), and sort () methods. In main (), call reverse () and sort () to process the word, and then the processing result is displayed.

Package ch07;
Import java. io. BufferedReader;
Import java. io. FileNotFoundException;
Import java. io. FileReader;
Import java. io. IOException;
Import java. io. PipedReader;
Import java. io. PipedWriter;
Import java. io. PrintWriter;
Import java. io. Reader;

Import ch07.ReverseThread;
Import ch07.SortThread;
Public class RhymingWords {
Public static void main (String [] args) throws IOException {
String pathname = "E :\\ workspace \ tmpfile \ words.txt ";
FileReader words = new FileReader (pathname );
// Restore words in reverse order
Reader rhymedWords = reverse (sort (reverse (words )));
// Output the processed word list
BufferedReader in = new BufferedReader (rhymedWords );
String input;
While (input = in. readLine ())! = Null)
System. out. println (input );
In. close ();


}
// Create an MPS queue, create and start the reverse word thread
Public static Reader reverse (Reader source) throws IOException {
BufferedReader in = new BufferedReader (source );
PipedWriter pipeOut = new PipedWriter ();
PipedReader pipeIn = new PipedReader (pipeOut );
PrintWriter out = new PrintWriter (pipeOut );
New ReverseThread (out, in). start ();
Return pipeIn;
}
Public static Reader sort (Reader source) throws IOException {
BufferedReader in = new BufferedReader (source );
PipedWriter pipeOut = new PipedWriter ();
PipedReader pipeIn = new PipedReader (pipeOut );
PrintWriter out = new PrintWriter (pipeOut );
New SortThread (out, in). start ();
Return pipeIn;
}
}

ReverseThread. java: The Thread class that executes the reverse order.

Package ch07; import java. io. bufferedReader; import java. io. IOException; import java. io. printWriter; public class ReverseThread extends Thread {private PrintWriter out = null; private BufferedReader in = null; public ReverseThread (PrintWriter out, BufferedReader in) {this. out = out; this. in = in;} // The public void run () {if (out! = Null & in! = Null) {try {String input; while (input = in. readLine ())! = Null) {out. println (reverseIt (input); out. flush ();} out. close ();} catch (IOException e) {System. out. println ("ReverseThread run" + e); // TODO: handle exception }}// implements the private String reverseIt (String rawWord) {int I, len = rawWord. length (); StringBuffer dest = new StringBuffer (len); for (I = (len-1); I> = 0; I --) {dest. append (rawWord. charAt (I);} return dest. toString ();}}

SortThread. java: Specifies the Thread class for sorting.

Package ch07; import java. io. bufferedReader; import java. io. IOException; import java. io. printWriter; public class SortThread extends Thread {private PrintWriter out = null; private BufferedReader in = null; public SortThread (PrintWriter out, BufferedReader in) {this. in = in; this. out = out;} // The public void run () {int MAXWORDS = 50; if (out! = Null & in! = Null) {try {String [] listOfWords = new String [MAXWORDS]; int numWords = 0; while (listOfWords [numWords] = in. readLine ())! = Null) {numWords ++;} quickSort (listOfWords, 0, numWords-1); for (int I = 0; I <numWords; I ++) out. println (listOfWords [I]); out. close ();} catch (IOException e) {// TODO: handle exceptionSystem. out. println ("SortThread run:" + e );}}}
// Implement fast sorting private static void quickSort (String [] a, int lo0, int hi0) {int lo = lo0; int hi = hi0; if (lo> = hi) return; String mid = a [(lo + hi)/2]; while (lo

In this example, words.txt contains the following words:

The program running result is:

Enable rhyme processing.

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.