Dark Horse programmer-java Basic-io (i)

Source: Internet
Author: User
Tags readfile

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

I. Overview

The Java I/O system is responsible for processing the input and output of the program, the I/O class library is located in the Java.io package, which abstracts the various common input and output streams. If the smallest unit of data in the data stream is a byte, then the stream is called a word stream, and if the smallest unit of data in the stream is a character, it is called a stream of characters. In the I/O class library, Java.io.InputStream and java.io.OutputStream represent byte input streams and byte output streams respectively, and Java.io.Reader and java.io.Writer represent character input streams and character output streams, respectively. We sometimes refer to InputStream and outputstream directly as input and output streams, while for Reader and Writer, they use their English class names directly. The common base classes for IO streams are as follows:

Abstract base class for byte stream: InputStream, OutputStream

Abstract base class for character streams: Reader, Writer

The difference between the byte stream and the character stream: The early is the byte stream, the data manifests the form all is bytes (binary data), in order to facilitate to the "text data" the processing, solves the question which the code table queries, has produced the character stream. The character stream is based on a byte stream, and the encoded table is fused in the character stream object. As a result, the byte stream can handle media files (such as pictures, videos), and character streams are used only to process text files (i.e. text data).

First, the text

1 , Byte stream

1.1 InputStream

InputStream is an abstract class that itself cannot create an instance to perform the input, which contains the following methods:

1.Int Read (): reads a single byte from the input stream and returns the byte data read. 2.int Read (byte[] b): reads up to b.length bytes of data from the input stream and stores it in byte array B, returning the actual number of bytes read. 3.int Read (byte[] b,int off,int len): reads up to len bytes of data from the input stream and stores it in array B, when placed in array B, not starting from the beginning of the array, but starting from the off position, returning the actual number of bytes read. 4. int available () throws IOException: Returns the number of valid bytes in the stream. 5. Long Skip (long N) throws IOException: Ignores numbytes bytes, returns the number of bytes actually ignored 6.abstract void close () throws IOException: closes the input stream

The FileInputStream class (file input Class) is the implementation subclass: it creates a InputStream class that reads bytes from a file, and is commonly constructed by:

FileInputStream (String filepath);

FileInputStream (File fileobject);

Here is a piece of code that uses FileInputStream to display the contents of a specified text file "Read.txt".

Class test1{    Text1 (InputStream in) throws exception{    int len = in.available ();    Byte[] B = new Byte[len];    In.read (b);    System.out.println (New String (b));    In.close ();    }    public static void Main (string[] args) throws exception{       new Text1 (New FileInputStream ("Read.txt"));}    }


1.2 OutputStream

This abstract class is a superclass of all classes that represent the output byte stream. The output stream accepts output bytes and sends those bytes to a sink, which is commonly used in the following ways:

1.void Close (): closes this output stream and frees all system resources related to this stream. 2.void Flush (): refreshes this output stream and forces all buffered output bytes to be written out. 3.void write (byte[] b): writes B.length bytes from a specified byte array to this output       stream. 4.void write (byte[] b, int off, int len: Shifts the specified byte array from offset to off         

The FileOutputStream class (File output Class) is a common implementation subclass: it creates a class outputstream that can be written to a file, commonly constructed by:

FileOutputStream (String filepath);

FileOutputStream (File fileobject);

FileOutputStream (String filepath,boolean append), where append is true, indicates that a write is appended to the original file, which begins at the end of the file. Otherwise, the write starts at the beginning of the file.

Here's a simple practice code:

Class copy{       Copy (InputStream in,outputstream out) throws ioexception{        int b;        while ((b = In.read ())! =-1) {        out.write (b);        }        In.close ();        Out.close ();        }        public static void Main (string[] args) throws ioexception{        new Copy (system.in, System.out);}        }

1.3-byte throttle buffer

Buffer technology improves the reading and writing efficiency of the byte stream. It's two ways:

1. Read (): The byte byte value is promoted to type int

2. Write (): The int is strongly converted to byte type, that is, the last eight bits of the binary number are preserved.

The following steps are described:

    1. The bytes of the fixed array length are fetched from the data, stored in the defined array, and then the elements in the array are read through the read () method and stored in the buffer.
    2. Loop this action until you finally take out a set of data into the array, the array may not be filled, and the contained elements are also taken out.
    3. Each time it is removed, a pointer is moved, and the end of the array is automatically returned to the array header, so that the pointer is self-increasing.
    4. When taken out, the elements in the array are reduced, one is removed, and one is reduced until the element is reduced to 0.
    5. When all the data in the file is read out, the Read () method returns-1.

2 , character Stream

2.1 Reader

Reader is the abstract class of the literal Java flow character input pattern, the following methods are mainly

1.abstract void Close (): function: Turn off the input source. Further reading will result in ioexception;2.void mark (int numChars): function: Set a flag at the current position of the input stream. The input is valid before NumChars characters are read; 3.boolean marksupported (): function: This stream supports Mark ()/reset () returns True;4.int read () : function: Returns an integer if the next character of the input stream being called is readable. Returns -1;5.int read (char buffer[]) when the end of the file is encountered: An attempt was made to read the buffer.length word Fu in buffer, returning the number of characters actually successfully read. Returns -1;6.abstract int read (char buffer[],int offset,int numChars) When the end of the file is encountered: An attempt was made to read Buffer[offset characters starting from numChars] in buffer, Returns the number of characters actually read successfully. Encountered end of file return -1;7.boolean ready (): function: Returns True if the next input request does not wait, otherwise returns False;8.long skip (long NumChars): function: Skips numChars input characters, Returns the skipped character set input pointer to the previously established flag.

The FileReader class creates a reader class that can read the contents of a file. Construction Method:

FileReader (String filepath);

FileReader (File fileobject);

Here is a practice code:

public class Writerreadertest {       file F=new file ("E:\\abc.txt");          public static void Main (string[] args) throws ioexception{         writerreadertest test=new writerreadertest ();         Test.writefile ("Java character stream read and write file test!");         Test.readfile ();     }           private void ReadFile ()  throws ioexception{         Reader r=new bufferedreader (new FileReader (f));                   int temp=0;             String str= "";                      while ((Temp=r.read ())!=-1) {                    str+= (char) temp;         }                System.out.println ("File content:" +str);     }           private void WriteFile (String content) throws IOException {         if (f.exists () ==false) {             f.createnewfile ();        }                Writer w=new FileWriter (f);                W.write (content);                 W.flush ();            W.close ();     } }

2.2 Writer

Write is an abstract class that defines the output of a stream character, and all methods of that class return a void value and IOException the exception under the condition of the error. The main methods are as follows:

1.void Close (): function: Turn off output stream 2.void flush (): function: Refresh output buffer 3.void write (int ch): function: Finalize single word Fu to output. Note that the parameter is an integer, and the designer does not have to convert the argument into a character type to be able to call the Write () method 4.void write (char buffer[]): function: Write a complete character array to an output stream 5.void Wirte (char Buffer[],int offset,int NumChars): function: Writes the output stream of the call to the array buffer to Buffer[offset] as the starting point for content within the white N numChars region. 6.void write (String str): function: Writes a string str;7.void write to the invoked stream (string Str,int offset,int numChars) : function: Writes the contents of the array str with the specified offset as the starting point of the NumChars character area

The FileWriter class creates a writer class that can write files, constructing methods:

FileWriter (String FilePath)

FileWriter (String Filepath,boolean append)

FileWrite (File fileobj);

Here is a practice code:

public static void Main (string[] args) throws IOException {     String str = ' Hello world!!! ';    char[] buffer = new char[str.length ()];    Str.getchars (0, Str.length (), buffer, 0);       FileWriter FW = new FileWriter ("D:/itzhai/arthinking.txt");     for (int i=0; i<buffer.length; i++) {        fw.write (buffer[i]);    }    Fw.close ();     Create FileReader    bufferedreader br = new BufferedReader (    new FileReader ("D:/itzhai/arthinking.txt"));    Reads a file    while (null! = (str = br.readline ())) {        System.out.println (str)) using the progressive read function provided by BufferedReader;    }    Br.close ();}

2.3-Character stream buffers--bufferedreader and BufferedWriter

Buffers increase the read and write efficiency of a stream, so you create a stream object before the buffer is created. That is, the stream object is first initialized into the constructor.

The specific implementation steps of the buffer technology are as follows:

    1. To write to the stream buffer BufferedWriter:

1.1 Creates a character to write to the stream object.

such as: FileWriter Fw=newfilewriter ("Buf.txt");

1.2 In order to improve the character write stream efficiency. Added buffer technology. Simply pass the stream object that needs to be improved as an argument to the constructor of the buffer.

such as: BufferedWriter BUFW =new BufferedWriter (FW);

1.3 Calling the Write method to write data to the specified file

such as: Bufw.write ("ADFG");

1.4 Actually closes the buffer, which is the stream object in the close buffer.

such as: Bufw.close ();

2. Read the stream buffer BufferedReader step

2.1 Create a read stream object and file associated

such as: FileReader Fr=newfilereader ("Buf.txt");

2.2 To improve efficiency. Added buffer technology. The constructor that passes the character read stream object as a parameter to the buffer object.

such as: BufferedReader bufr=new BufferedReader (FR);

2.3 Calls the buffer provided by the ReadLine method to read one line at a time and returns null if the end of the file is reached

such as: String S=bufr.readline ();

2.4 Closing Streaming resources

such as: Bufr.close ();

3 , conversion flow

The conversion stream is a bridge between the character stream and the byte stream, which facilitates the operation between the character stream and the byte stream. Application of the conversion stream: when the data in a byte stream is a character, it is more efficient to turn into a character stream operation.

InputStreamReader is the flow of bytes to a character stream, such as keyboard entry the most common notation is:

Bufferedreaderin=newbufferedreader (New InputStreamReader (system.in));

OutputStreamWriter is the flow of characters to a byte stream. In general, conversion flows are required when character encoding conversions are involved.

So how to do the flow operation, through three clear to complete:

1. Clear source and purpose.

Source: input stream. InputStream Reader

Purpose: The output stream. OutputStream Writer

2. Whether the manipulated data is plain text.

Yes: Character stream

No: Byte stream

3. When the system is clear, then specify which specific object to use. To differentiate by device:

SOURCE device: Memory, hard disk, keyboard

Purpose device: Memory, HDD, console

Here's a simple practice code:

public class Inputstreamreaderdemo {public    static void Main (string[] args) throws IOException {        //get standard input stream        InputStream in = system.in;        Converts a byte stream to a character stream        InputStreamReader ISR = new InputStreamReader (in);        Decorate the character stream        bufferedreader br = new BufferedReader (ISR);        string string =null;        while ((String=br.readline ())!=null) {            if (' over '. Equals (String)} {break                ;            }            System.out.println (String.touppercase ());        }    }

Third, Summary

This paper mainly introduces the basic framework of IO flow, namely, four base classes InputStream, OutputStream and Reader, Writer, and their corresponding cache technology, that is, the so-called decorator mode, which improves the efficiency of IO. Finally, the conversion stream is simply the one that enables the conversion of the byte stream and the character stream to each other.

Dark Horse programmer-java Basic-io (i)

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.