Dark Horse Programmer----Java Basics: IO

Source: Internet
Author: User

-------Android Training, Java training, look forward to communicating with you! ----------

Concept

Flow: A stream is an abstraction of a sequence of bytes, a data source that can be continuously read, and a stream that can be continuously written to the data.

IO stream: Used to process data on the device

Common equipment: Hard disk, memory, keyboard input, etc.

Classification of IO streams:

1, according to the processing data types, can be divided into byte stream and character stream.

2, according to the flow of different flows, can be divided into input stream and output stream.

Io system inheritance Diagram

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6E/3A/wKiom1V2oq6iuBrtAAIckRDqueI270.jpg "title=" 221107294082567.jpg "alt=" Wkiom1v2oq6iubrtaaickrdquei270.jpg "/>

Function

The IO system has the most basic two functions: Read and write.

1, Byte stream: InputStream (Read) and OutputStream (write).

2, Character stream: Reader (read) and writer (write).

Basic read and write operations for character streams: Reader and writer

Inheritance Relationship:

Reader

InputStreamReader

FileReader: A character read stream object dedicated to processing files

Writer

Outputstreamreader

FileWriter: Writes a Stream object specifically for processing the file's characters

Common methods in Reader:

1, int read (): reads a character and returns the character read. Returns 1 if the end of the stream has been read;

2, int Raad (char[]): The read to the character into the specified array of characters, return the number of characters read, if you have read to the end of the stream, then return-1;

3. Close (): Close the stream and release the resource.

Common methods in Writer:

1. Write (CH): writes a character to the stream.

2. Write (char[]): Writes a character array to the stream.

3. Write (String): Writes a string to the stream.

4. Flush (): Flushes the data in the stream to the data destination, and the stream still exists.

5, Close (): Close the stream. The data in the stream is flush () into the data destination before the resource is closed.

FileReader:

1. The stream object used to read the text file.

2, for associating text file.

Constructor: FileReader (String fileName);

When the read stream object is initialized, a read file must be specified.

FileNotFoundException occurs if the file does not exist

FileWriter:

1. For working with text files

2. There is a default encoding table in this class

3. There is a temporary buffer in this class

Constructor: FileWriter (String fileName)

When writing to the stream object initialization, you must specify a destination to store the data. If the file does not exist, the system creates a file. If the file exists, it will be overwritten.

FileWriter (String filename,boolean Append):

When Append is true, the data continues to be written at the end of the file.

code example: Copy a text file from drive C to the D drive.

The principle of copying: In fact, the C disk under the file data is stored in a file d.

Steps:

1, create a file in the D drive. Used to store data in a C-drive file.

2, define read stream and C-Drive file association.

3, through continuous reading and writing to complete the data storage.

4, close the resource.

The first method:

Import java.io.*;

Class CopyText

{

public static void Main (string[] args) throws IOException

{

Copy_2 ();

}

public static void Copy_2 ()

{

FileWriter FW = NULL;

FileReader FR = null;

Try

{

FW = new FileWriter ("Systemdemo_copy.txt");

FR = new FileReader ("Systemdemo.java");

char[] buf = new char[1024];

int len = 0;

while ((Len=fr.read (BUF))!=-1)

{

Fw.write (Buf,0,len);

}

}

catch (IOException E)

{

throw new RuntimeException ("Read and Write Failed");

}

Finally

{

if (fr!=null)

Try

{

Fr.close ();

}

catch (IOException E)

{

}

if (fw!=null)

Try

{

Fw.close ();

}

catch (IOException E)

{

}

}

}

The second method: read a character from the C drive and write a character to the D drive.

public static void Copy_1 () throws IOException

{

Create a destination.

FileWriter FW = new FileWriter ("Runtimedemo_copy.txt");

Associated with an existing file.

FileReader FR = new FileReader ("Runtimedemo.java");

int ch = 0;

while ((Ch=fr.read ())!=-1)

{

Fw.write (CH);

}

Fw.close ();

Fr.close ();

}

}


The buffer of the character stream:

The presence of buffers increases the operational efficiency of the convection, and the principle of its implementation is to encapsulate the internal array.

The corresponding object:

BufferedReader

Unique Method: ReadLine (): reads one line at a time, reads the line tag, returns the string before the row tag, and returns NULL when the end is read.

BufferedWriter

Unique Method: NewLine (): cross-platform newline character, used to write a newline character into the stream.


Using a buffer technology instance: copy A. java file through a buffer.

Import java.io.*;

Class Copytextbybuf

{

public static void Main (string[] args)

{

BufferedReader bufr = null;

BufferedWriter BUFW = null;

Try

{

BUFR = new BufferedReader (New FileReader ("Bufferedwriterdemo.java"));

BUFW = new BufferedWriter (New FileWriter ("Bufwriter_copy.txt"));

String line = null;

while ((Line=bufr.readline ())!=null)

{

Bufw.write (line);

Bufw.newline ();

Bufw.flush ();

}

}

catch (IOException E)

{

throw new RuntimeException ("Read and Write Failed");

}

Finally

{

Try

{

if (bufr!=null)

Bufr.close ();

}

catch (IOException E)

{

throw new RuntimeException ("Read shutdown failed");

}

Try

{

if (bufw!=null)

Bufw.close ();

}

catch (IOException E)

{

throw new RuntimeException ("Write shutdown failed");

}

}

}

}


Read and write operation for byte stream:

InputStream and OutputStream

A byte stream can manipulate any data.

For example, copy the code for a section of the MP3 file in a buffer:

/*

Demonstrates replication of MP3. Through the buffer.

Bufferedoutputstream

Bufferedinputstream

To simplify the code, throw the exception.

*/

Import java.io.*;

Class CopyMp3

{

public static void Main (string[] args) throws IOException

{

Long start = System.currenttimemillis ();

Copy_1 ();

Long end = System.currenttimemillis ();

System.out.println ((End-start) + "MS");

}

public static void Copy_1 () throws IOException

{

Bufferedinputstream Bufis = new Bufferedinputstream (New FileInputStream ("C:\\0.mp3"));

Bufferedoutputstream Bufos = new Bufferedoutputstream (New FileOutputStream ("C:\\1.mp3"));

int by = 0;

while ((By=bufis.read ())!=-1)

{

Bufos.write (by);

}

Bufos.close ();

Bufis.close ();

}

}


Conversion Flow:

Characteristics:

1. Is the bridge between the byte stream and the character stream.

2, the Stream object can be read to the byte data to the specified encoding table encoding conversion.

Scope of Use

1. When there is a conversion action between the byte and the character.

2, stream operation of the data needs to be encoded when the table is specified.

The specific object embodies:

1, InputStreamReader: byte-to-character bridge.

2, OutputStreamWriter: The character to the byte of the bridge.

constructor function:

InputStreamReader (InputStream): Through this constructor initialization, using the system is the default encoding table GBK.

InputStreamReader (inputstream,string charSet): Through this constructor initialization, you can specify the encoding table.

OutputStreamWriter (OutputStream): Through this constructor initialization, using the system is the default encoding table GBK.

OutputStreamWriter (outputstream,string charSet): Through this constructor initialization, you can specify the encoding table. The character stream object of an action file is a subclass of the transform stream.

The Read method in the transform stream. has been integrated into the Code table, the underlying invocation of the Read method of the byte stream will fetch one or more bytes of data to be stored temporarily, and to check the specified encoding table, if the encoding table is not specified, check the default Code table. Then the Read method of the stream can return a character such as Chinese. The conversion stream has completed the encoding conversion action, for the direct operation of the text file of the Filereaer, it is not redefined, as long as the transformation stream, to obtain its method, you can directly manipulate the text file in the character data.

Basic rules of flow operation:

1, clear data source and data purposes. In fact, the input stream or output stream is defined.

2, the clear operation of the data is plain text data. In fact, it is to clarify the character stream or byte flow.

Data Source: Keyboard system.in, hard disk (stream object at the beginning of file), memory (array).

Data purpose: Console System.out, hard disk (stream object at the beginning of file), memory (array).

This article is from the "Dot Drop" blog, please be sure to keep this source http://arctictern.blog.51cto.com/10120640/1660117

Dark Horse Programmer----Java Basics: IO

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.