"Go" input/output stream-Fully master IO

Source: Internet
Author: User
Tags array to string

File class:

The Operation files and directories in the program can be done using the file class, that is, whether the files or directories are used to manipulate the document class, file can create new, delete, rename files and directories, but file cannot access the content itself, if you need to access the file itself, you need to use the input/output stream, The class is located under the Java.io package.

Input and Output IO:

Input stream: Data can only be read from, not written to (by InputStream (Byte stream) and reader (character stream) as the base class)

Output stream: Data can only be written to, not read from (OutputStream (byte stream) and writer (character stream) as base class)

Java's IO involves a total of more than 40 classes, but is derived from these four abstract base classes

InputStream the three most important read methods:

Read method in Reader:

From the two abstract classes provided by the method can be seen in fact, the function is basically the same, but the operation of the data unit is not the same

Since both InputStream and reader are abstract classes and cannot be instantiated, we can only create instances with their subclasses, which provide a subclass of input stream for reading the file: FileInputStream and

FileReader, these two subclasses are node streams (relative to the processing stream)-----are directly associated with the specified file without wrapping. The following code shows FileInputStream using read (byte[] b):

Package Xidian.sl.io;import Java.io.fileinputstream;import Java.io.filereader;public class Inputstreamtest {/** * Use FileInputStream to read the class itself * */public static void Fileinputstreamtest () throws exception{FileInputStream FIS        = NULL;        try{//create byte input stream fis = new FileInputStream ("Src/xidian/sl/io/inputstreamtest.java");        Create a byte array of length 1024 to access byte[] Bbuf = new byte[1024];        The number of bytes used to hold the actual read int hasread = 0; Use loops for repeated reads while ((Hasread = Fis.read (bbuf)) > 0) {//Take out bytes, convert byte array to string output System.out.printl        N (New String (bbuf, 0, Hasread));        }}finally{//close file Input stream fis.close (); }}/** * Read the class itself using FileReader * */public static void Filereadertest () throws exception{Filere        Ader FR = null;        try{//create byte input stream fr = new FileReader ("Src/xidian/sl/io/inputstreamtest.java"); Create a byte array of length 1024 to access char[] Bbuf = new CHAR[40];        The number of bytes used to hold the actual read int hasread = 0; Use loops for repeated reads while ((Hasread = Fr.read (bbuf)) > 0) {//Take out bytes, convert byte array to string output System.out.println        (New String (bbuf, 0, Hasread));        }}finally{//close file Input stream fr.close ();        }} public static void Main (string[] args) throws exception{inputstreamtest.fileinputstreamtest ();    Inputstreamtest.filereadertest (); }}

You can see that the use of these two sub-classes can be said to be exactly the same, but there is a problem: byte stream FileInputStream is read according to bytes, and a Chinese is two bytes, if the file contains a lot of Chinese is read by the byte stream, may cause garbled, Because it may lead to just a Chinese two times read, so it will be garbled, so if the Chinese contains more words or use character stream FileReader is better,

The rule of choice between the byte stream and the character stream: if the input/output content is text content, you should consider using a character stream, if you need to input/output binary content, you should consider using a byte stream, because the function of the byte stream is more powerful than the character stream, all the data in the computer is binary, and the byte stream can handle all binary files;

The most important write method in OutputStream:

The most important write method in writer:

Writer class has more than two pairs of string operation class, so if the direct output string to choose Writer will be more convenient;

As with the input stream, the output stream also has a subclass of two file operations: FileOutputStream and FileWrite

Package Xidian.sl.io;import Java.io.fileinputstream;import Java.io.fileoutputstream;import java.io.FileWriter; public class Outputstreamtest {/** * uses byte stream output * */public static void Fileoutputstreamtest () throws Exceptio        n{FileInputStream FIS = null;        FileOutputStream fos = null;            try{//create byte input stream fis = new FileInputStream ("Src/xidian/sl/io/inputstreamtest.java");            Create byte output stream fos = new FileOutputStream ("Src/xidian/sl/io/output.txt");            byte[] bt = new BYTE[40];            int hasread = 0; Loops read data from the input stream while ((Hasread = Fis.read (BT)) > 0) {//per read one, that is, write to the file output stream, read as much as you write how many fo            S.write (BT, 0, Hasread);        }}catch (Exception e) {e.printstacktrace ();            }finally{/** * Stream will automatically execute flash when it is closed, flush data from the buffer into the physical node * so it's important to close * */    if (FIS! = null) {fis.close ();        } if (fos! = null) {fos.close (); }}}/** * using a character stream to output a string is easier to compare * */public static void Filewritetest () throws exception{Fi        Lewriter FW = NULL;            try{//create byte output stream fw = new FileWriter ("Src/xidian/sl/io/output.txt");            Fw.write ("Wenzhou Medical college \ r \ n");            Fw.write ("Information and management specialty \ r \ n");            Fw.write ("Wenzhou Medical college \ r \ n");            Fw.write ("Wenzhou Medical college \ n");        Fw.write ("Wenzhou Medical College");        }catch (Exception e) {e.printstacktrace ();            }finally{if (fw! = null) {fw.close (); }}} public static void Main (string[] args) throws exception{Outputstreamtest.fileoutputstreamtest ()        ;    Outputstreamtest.filewritetest (); }}


Above is the basic use of the node stream, the following will understand the use of processing flow, processing flow will be more efficient

The way to differentiate a node from the process flow is that as long as the parameter of the constructor of the stream is not a physical node, but the existing stream, that flow must be the processing stream, because all the node flows are directly with the physical IO node as the constructor parameters,

(such as file).

Example: PrintStream processing flow to encapsulate FileOutputStream node stream, output, because the output of PrintStream class is very powerful, so we need to output text content generally will be wrapped in output stream printstream output

Package Xidian.sl.io;import Java.io.fileoutputstream;import Java.io.printstream;public class PrintStreamTest {    public static void Main (string[] args) {        PrintStream PS = null;        try{            //Create a node output stream            fileoutputstream fos = new FileOutputStream ("Src/xidian/sl/io/output.txt");            The FileOutputStream node stream            PS = new PrintStream (FOS) is wrapped in a printstream processing stream;            Ps.println ("normal string");            Ps.println (New Printstreamtest ());        } catch (Exception e) {            e.printstacktrace ();        } finally{            ps.close ();}}}    

In fact, the type of standard output system.out we have been using is PrintStream:

From the above example, it can be seen that it is very simple to encapsulate the node stream into a processing stream, just call the construction method of the processing stream to pass in the node stream, and see that the flow is closed just to close the flow of the stream and not to close the node stream, which is exactly right, we just need to close the topmost processing stream ;

There are two special streams in the character stream to handle strings: StringReader and StringWriter,

You can see that using the instantiation only needs to pass in a string: example:

Package Xidian.sl.io;import Java.io.stringreader;import Java.io.stringwriter;public class Stringnodetest {    /**     * @param args */public    static void Main (string[] args) {        //TODO auto-generated method stub        String s rc = "You are a god";        StringReader sr = new StringReader (SRC);        char[] chars = new CHAR[40];        int hasread = 0;        try{            //uses a cyclic way while            ((Hasread = Sr.read (chars)) >0) {                System.out.println (new String (chars, 0, Hasread));            }        } catch (Exception e) {            e.printstacktrace ();        } finally{            sr.close ();        }        Create StringWriter        StringWriter sw = new StringWriter (+);        Sw.write ("You are a great God");        Sw.write ("You are also a great God");        System.out.println (Sw.tostring ());}            }


The IO system provides two conversion streams: InputStreamReader and OutputStreamWriter, all of which convert bytes to a character stream

In Java, system.in is used to provide keyboard input, but this standard input stream is an instance of the InputStream class:

And before that, when dealing with text content, it would be convenient to use a character stream, just as the keyboard input is the operation of the text, so we have to convert system.in to a character stream:

 package xidian.sl.io;import java.io.bufferedreader;import java.io.IOException Import Java.io.inputstreamreader;public class Keyintest {public static void main (string[] args) {Bufferedreade        R br = NULL;            try{//Convert System.in object to reader object InputStreamReader ISR = new InputStreamReader (system.in);            Wraps the node stream as a processing stream br = new BufferedReader (ISR);            String buffer = null;            Reads a row line in a loop (buffer = Br.readline ()) = null) {System.out.print ("input =" + buffer);        }}catch (Exception e) {e.printstacktrace ();            }finally{try {br.close ();            } catch (IOException e) {e.printstacktrace (); }        }    }}

PrintStream is a powerful output function, and Bufferreader has a strong input (that is, read), so when the operation to read the text content as far as possible to convert it to Bufferreader, you can easily use the ReadLine () method

The next most powerful file operation class Randomaccessfile come, this class can either input data to the file, can also output data, and he is the most different from different streams is "Support files anywhere access", that is, the program can control where to read the contents of the file;

As can be seen from the construction method, in addition to providing a file or file name also need to provide a string parameter Mode,mode specifies the Randomaccessfile class access to the file mode:

1. "R": Open the specified file in read-only mode

2. "RW": Opens the specified file in read, write mode, and the file does not exist automatically created

3. "RWS" and "RWD": Similar to "RW", only requires that each update of the file content or metadata be written to the underlying storage device synchronously

"Go" input/output stream-Fully master IO

Related Article

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.