Java full reference manual (version 8th) Chapter 1 I/O Overview

Source: Internet
Author: User

1,The behavior of all streams is the same. You can apply the same I/O classes and methods to any type of devices, and abstract many different types of input-disk files, keyboards, or network sockets as input streams. The output stream can reference the console, disk files, or network links.

Two types of streams are available: byte streams and byte streams. Byte stream processes the input and output of byte (such as binary data), bytes stream processing characters, Unicode, and internationalization. In some cases, compaction streams are more efficient than word throttling.

At the bottom layer, All I/O is still byte-oriented. Character-based stream only provides a convenient and efficient way to process characters.

2. byte stream class.

Top-level abstract classes: inputstream and outputstream. Each abstract class has several specific sub-classes that process different devices, such as disk files, network links, and even memory caches.

For the byte stream class in Java. Io, see: http://docs.oracle.com/javase/6/docs/api/java/io/package-summary.html

  • BufferedinputstreamCacheInput stream
  • Bufferedoutputstream
  • Bytearrayinputstream readByte arrayContent input stream
  • Bytearrayoutputstream
  • Datainputstream contains readJava Standard Data TypeMethod input stream
  • Dataoutputstream
  • Fileinputstream readingFile ContentInput stream
  • Fileoutputstream
  • FilterinputstreamImplement inputstream
  • Filteroutputstream
  • InputstreamAbstract class
  • Outputstream
  • Objectinputstream is usedObjectInput stream
  • Objectoutputstream
  • Pipedinputstream InputMPs queue
  • Pipedoutputstream
  • Printstream contains print () and println () output streams
  • Pushbackinputstream supports an input stream of the byte "unget", which returns 1 byte to the input stream
  • Sequenceinputstream is composed of two or more input streams read in sequence.

Abstract classes inputstream and outputstream define some key methods for implementing other stream classes. The most important of them are read () and write (). The derived stream classes must override these two methods.

3. Producer stream class.

Top-level abstract classes: reader and writer. Process unicode sequence streams.

For the pipeline stream class in Java. Io, see: http://docs.oracle.com/javase/6/docs/api/java/io/package-summary.html

Inputstream-> reader outputstream-> writer

  • BufferedreaderCacheInput streams
  • Bufferedwriter
  • Chararrayreader
    ReadCharacter arrayContent input stream
  • Chararraywriter
  • Datainputstream contains the input stream for reading java standard data type methods
  • Dataoutputstream
  • Filereader readingFile ContentInput stream
  • Filewriter
  • FilterreaderImplement inputstream
  • Filterwriter
  • InputstreamAbstract class
  • Outputstream
  • The abstract class that reader describes the input of a sequence stream.
  • Writer
  • Objectinputstream is used for the input stream of an object.
  • Objectoutputstream
  • Pipedreader
    InputMPs queue
  • Pipedwriter
  • Printwriter contains print () and println () output streams
  • Pushbackreader allows characters to return to the input stream of the input stream
  • Sequenceinputstream is composed of two or more input streams read in sequence.
  • Input stream for linenumberreader to calculate the number of rows
  • Inputstreamreader converts bytes into character input streams
  • Outputstreamwriter converts a character into a byte output stream
  • Input stream of stringreader reading content from string
  • Output stream of content written by stringwriter to a string

4. predefine a stream.

System class.See: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html

You can use this method to obtain the current time and various system-related property settings.

It also contains three predefined stream variables: In, out, and err. These variables are declared as public, static, and final in the system class.

System. arraycopyExample: http://blog.csdn.net/java2000_net/article/details/4059465

System. In isInputstream type object, System. Out and system. Err arePrintstream objects.All are byte streams.

  • To obtain the character-based stream associated with the console, You can encapsulate system. In in the bufferedreader object. Constructor: bufferedreader (Reader inputreader) inputreader is a stream linked to the bufferedreader instance to be created. Reader is an abstract class, And inputstreamreader is a subclass of it. It converts bytes into characters. The following is the object for creating a keyboard connection: bufferedreader BR = new bufferedreader (NewInputstreamreader (system. In)).
  • Example:
    // Use a bufferedreader to read characters from console. import Java. io. *; Class brread {public static void main (string ARGs []) throws ioexception {char C; bufferedreader BR = new bufferedreader (New inputstreamreader (system. in); system. out. println ("Enter characters, 'q' to quit. "); do {c = (char) Br. read (); // read a character from the input stream and return it as an integer value. If it reaches the end of the stream, return-1system. out. println (c);} while (C! = 'Q') ;}}// output: by default, system. In is cached by row, and no input is passed to the program before pressing enter. So when Q is multiple .. Enter characters, 'q' to quit.1234adfadqqq1234adfadq
  • Read the string. You can useReadline () method of bufferedreader class, As follows: String Readline () throws ioexception
  • Printstream is the output stream derived from outputstream, so it also implements a low-level write () method. Void write (INT byteval) outputs the byte specified by byteval. Although byteval is declared as an integer, only the lower 8 bits are output. For example, system. Out. Write ('\ n ').

5. printwriter class.

Use the printwriter stream to output recommended methods to the console using Java. Is a character-based class.Make the actual application more internationalized.

Constructor: printwriter (outputstream, Boolean flushonnewline)

Supports print () and println () methods.

A printwriter: printwriter PW = new printwriter (system. Out, true) is created );

6. Read and Write files.

Most commonly used fileinputstream and fileoutputstream. Create a byte stream connected to the file. Throws filenotfoundexception.

Security Manager (such as applet) may cause a securityexception.

After the file is used, it must be closed. The system resources allocated to the file will be released. If the file is closed, memory leakage will occur "(How to detect?)

<Memory leakage detection reference: http://hi.baidu.com/l_rigidity/item/6b161e102dbcfa9b99ce3305

Http://tech.ccidnet.com/art/3737/20081020/1594519_1.html

Http://wenku.baidu.com/view/bafcbc0690c69ec3d5bb7541.html>

File close void close () throws ioexception.

From JDK 7, the close () method is specified by the autocloseable interface in the Java. lang package. The closeable interface in the Java. Io package inherits the autocloseable interface. All stream classes implement these two interfaces.

Use a try statement with resources.Automatically close filesYou do not need to explicitly call the close () method.

Call the close () method in the finally code block. In this method, all methods for accessing files are included in the try code block, and the finally code block is used to close the file. Example:

Import java. Io. *; Class showfile {public static void main (string ARGs []) {int I; fileinputstream fin = NULL; If (ARGs. length! = 1) {system. out. println ("Usage: showfilename"); return;} // open file and read then closetry {fin = new fileinputstream (ARGs [0]); do {I = fin. read (); if (I! =-1) system. Out. println (char) I);} while (I! =-1);} catch (filenotfoundexception e) {system. out. println ("file not found. ");} catch (ioexception e) {system. out. println ("an I/O eror occurred");} finally {try {If (Fin! = NULL) Fin. Close (); // because the fin Initialization is null} catch (ioexception e) {system. Out. println ("error closing file ");}}}}

Copy an object using the write () method:

import java.io.*;class CopyFile {public static void main(String args[]) {int i;FileInputStream fin = null;FileOutputStream fout = null;if(args.length != 2) {System.out.println("Usage: Copyfile from to");return;}//copy a filetry {fin = new FileInputStream(args[0]);fout = new FileOutputStream(args[1]);do {i = fin.read();if(i != -1)  fout.write(i);} while(i != -1);} catch(IOException e) {System.out.println("I/O Error:" + e);} finally {try {if(fin != null)  fin.close();} catch(IOException e2) {System.out.println("Error Closing Input File");}try {if(fout != null)  fout.close();} catch(IOException e2) {System.out.println("Error Closing Output File");}}}}

Automatically close files:

Try (resource-Specification ){}. Only resources that implement the autocloseable interface can use try statements with resources. The resource scope is limited to the try statement block.Resources are implicitly declared as final and cannot be assigned to other resources. When you try to manage multiple resources, use semicolons to separate them.

When a resource is disabled in the finally clause, an exception in the try statement block may cause another exception. For regular try statements, the original exception is lost and replaced by the second exception. It is added toPending exception list. Defined by using throwableGetsuppresser ()Method to obtain the pending exception list.

Example:

import java.io.*;class ShowFile {public static void main(String args[]) {int i;if(args.length != 1) {System.out.println("Usage: Showfile filename");return;}try (FileInputStream fin = new FileInputStream(args[0])){do {i = fin.read();if(i != -1)  System.out.print((char)i);} while(i != -1);} catch(FileNotFoundException e) {System.out.println("File Not Found.");} catch(IOException e) {System.out.println("I/O Error Occurred." );}}}

On February 15

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.