"Interview Java IO Stream" Io__ interview

Source: Internet
Author: User
Tags file copy flush readline
I. IO

1.IO concept

• Input stream: The object that can read a byte sequence is called the input stream (Baidu Encyclopedia)

• Output stream: The object that can write a byte sequence is called the output stream (Baidu encyclopedia)

You might be confused by definition, and here's an explanation: input output is relative to the memory device, the peripheral (hard disk, keyboard, etc.) in the data read to the memory device called input, the memory device to write data to the peripherals called output, so there is read, write the salutation: Read into memory, write out memory.

It can be likened to this: the input stream and the output stream are connected to the memory, the input stream and the output stream are separated from the read-write operation, the memory is read from the peripheral, and then the memory is transferred to other peripherals.

• Overall structure (excerpt from netizens)


2. Byte throttling (using a byte stream to process character data can have coding problems, because the stream is in bytes, no coding, and the character streams are in characters for the transmission of data, the character stream is the word throttle + coding)

• Two top-level parent classes (abstract classes) and implementation classes

· InputStream (read in memory): Parent class for all byte input stream related classes

·· Fileinputstream:obtain input bytes from a file in a file system,for reading streams of raw bytes (raw bytes) such as image data .. For writing streams of Characters,consider using FileReader

When initializing (the constructor) to associate with the file, read the object first to determine whether the file exists

--read (): Read a byte of data from this inputstream.

--read (Byte [] b): Read up to b.length bytes of the data from this inputstream into an array of bytes.

--read (Byte [] b,int off,int length)

--close ()

Import java.io.*;
 /** * Created by the 2016/1/29.
        */public class Demo1 {public static void main (String [] args) {File file = new File ("D:/helloworld.txt");
        InputStream in = null;
            try {if (!file.exists ()) {//file does not exist create file.createnewfile ();
            } in = new FileInputStream (file);                 byte [] buf = new byte[1024];                         
            Write to the cache first and then write to the other peripherals with int length = 0;
                                                            while ((Length=in.read (BUF))!=-1) {//-1 represent the "end of" The file is reached, Byte one by one to read into memory System.out.println (new String (buf,0,length)); Need to convert int to byte, if you output garbled characters for Chinese,//Here is actually written to the peripheral (console), System.out return is print
        Stream object} catch (IOException e) {e.printstacktrace (); }finally {if (in!= null) {try {in.close ();
                catch (IOException e) {e.printstacktrace (); }
            }
        }
    }

·· Bytearrayinputstream: Contains a built-in buffer storage byte

constructor to be associated with a byte array: byte [] Buff

--read (): reads the next byte from the input stream

--read (Byte [] buff,int off,int len):

--close (): The method in the class can still be invoked without throwing an IO exception after the shutdown does not affect

· OutputStream (write out memory): The parent class of all and output byte-related classes

·· Fileoutputstream:for writing data to a file or a filedescriptor,for writing streams of raw data (raw bytes) such as image data. For writing streams of Characters,consider using FileWriter.

The destination to be associated with the file when initializing. The file is created automatically when it is not.

--write (int b): Write the specified (specified) byte to this file output stream.

--write (Byte [] b):

--write (Byte [] b,int off,int len)

--close ()

Import java.io.*;

/**
 * Created by the 2016/2/25.
 */Public
class Demo2 {public
    static void Main (String [] args) {
        file File = new File ("D:/helloworld3.txt"); 
  //no <span style= "font-family:kaiti_gb2312;" > will automatically create </span>
        outputstream out = null;
        try {out
            = new FileOutputStream (file);
            Out.write ();                    The character that produces the ASC code in the file is
        catch (IOException e) {
            e.printstacktrace ();
        } finally {
            try {
                out.close ( );
            } catch (IOException e) {
                e.printstacktrace ();}}}

★fileinputstream & FileOutputStream Cooperate to complete file copy (no garbled)

Import java.io.*;
 /** * Created by the 2016/2/25. * * public class Demo3 {/** * Copy from one file to another * @param args/public static void Main (String [] args
                {File origin = new file ("D:/helloworld.txt");//original file if (!origin.exists ()) {try {
            Origin.createnewfile ();
            catch (IOException e) {e.printstacktrace ();
        } File Destination = new file ("D:/helloworld4.txt");//destination InputStream in = null;
        OutputStream out = null;
            try {in = new FileInputStream (origin);
            out = new FileOutputStream (destination);
            byte [] buff = new byte[1024];
            int len = 0;
            while ((Len=in.read (Buff))!=-1) {out.write (Buff,0,len);
        } catch (IOException e) {e.printstacktrace (); Finally {try {if (in!= null) {In.cloSE ();
                } if (out!= null) {out.close ();
            } catch (IOException e) {e.printstacktrace ();
 }
        }
    }
}

3. Character streams

• Two top-level parent abstract classes and their implementation classes

· Reader:for reading character streams

·· InputStreamReader: A bridge from byte stream to character streams: reads a stream of bytes and decodes it by the specified encoding (can't read → can Read)

The constructor is associated with the input stream inputstream/encoding method charset: System.in/fileinputstream incoming

--read (): Read a character

--read (char [] cbuf,int offset,int length)

--close ()

··· FileReader: A convenient class for reading character files, essentially inputstreamreader specifies the default encoding at construction time to read character streams

constructor to be associated with a file

★inputstreamreader receive the data entered on the keyboard, write to the file (Chinese will garbled)

Import java.io.*;
 /** * Created by the 2016/2/25. * * public class Demo4 {/** * console input, written to folder * @param args/public static void Main (String [] args)
        {File File = new file ("D:/helloworld.txt");//overwrites previous data outputstream out = null;
        InputStreamReader reader = null;
            try {reader = new InputStreamReader (system.in);
            out = new FileOutputStream (file);
            int len = 0;
            while (len = Reader.read ())!=-1) {out.write (len);
        } catch (IOException e) {e.printstacktrace ();
                finally {if (out!=null) {try {out.close ();
                catch (IOException e) {e.printstacktrace ();
                } if (Reader!=null) {try {reader.close (); catch (IOException e) {E.printstacktraCE ();
 }
            }
        }

    }
}

·· BufferedReader: Reads text from a character input (Character-input) stream and buffers characters, default cache 8192 (8M), line length 80

constructor to associate with reader In/int size: inputstreamreader

--in Read ()

--in read (char [] cbuf,int off,int len)

--string ReadLine ()

--close ()

★ Keyboard input, use caching

BufferedReader BUFFR = new BufferedReader (new InputStreamReader (system.in))


· Writer:for writing to character streams (the write operation of a character stream is essentially followed by a flush () operation)

·· OutputStreamWriter: A bridge from character flow to byte stream: the characters written are encoded in the specified encoding.

Constructors are associated with OutputStream Out/charset: System.out/fileoutputstream

--write (int c): Write a separate character

--write (char [] cbuf,int off,int len)

--write (String str,int off,int len)

--flush (): Refreshing stream

--close ()

··· FileWriter: A convenient class for writing character files, in essence: outputstreamwriter Specifies the default native encoding and can process files

·· BufferedWriter: Writes text to a character output (Character-out) stream and caches incoming characters

constructor to be associated with Writer out/int size

--write (int c): Write a separate character

--write (char [] cbuf,int off,int len)

--write (String str,int off,int len)

--newline (): Wrapping

--flush (): Refreshing stream

--close ()

★ Console output, using caching

BufferedWriter buffw= New BufferedWriter (New OutputStreamWriter (System.out, "utf-8"));

★ Keyboard input, console output function

Import java.io.*;
 /** * Created by the 2016/2/26.
     
        * * public class Demo5 {/** * keyboard input, console output * @param args/public static void Main (String[]args) {
        BufferedReader buff = null;
        BufferedWriter bufferedwriter = null;
        String line = null;
            try {buff = new BufferedReader (new InputStreamReader (system.in, "utf-8"));
            BufferedWriter = new BufferedWriter (new OutputStreamWriter (System.out, "utf-8")); <span style= "Font-family:simsun;" >while</span> ((Line=buff.readline ())!=null) {bufferedwriter.write (line); <span style= "Font-fa mily:kaiti_gb2312; " > <span style= "Font-family:simsun;"         >}</span></span>   Bufferedwriter.flush ();
        Be sure to refresh the} catch (IOException e) {e.printstacktrace ();
                finally {if (buff!=null) {try {buff.close (); }catch (IOException e) {e.printstacktrace ();
                } if (Out!=null) {try {out.close ();
                catch (IOException e) {e.printstacktrace ();
 }
            }
        }

    }
}

☆ Interview questions: Briefly describe the steps to enter data from a file into another file

1. First create a file object, and associated with the file you want to manipulate, this time need to judge whether the file exists, does not exist will be an error

2. Since reads the file and writes to the file, belongs to the plain text, may choose FileReader and FileWriter to carry on reads and writes the operation, if appears garbled can use its parent class to specify the encoding way

3. Create a FileReader object to read the data in the file, where you can use the buffer stream for processing, improve efficiency, create a BufferedReader object

BufferedReader BUFFR = new BufferedReader (new InputStreamReader) (new FileReader (file));

4. Create FileWriter, ditto use cache

★ The code is as follows

Import java.io.*;
 /** * Created by the 2016/2/26.
        * * Public class Demo6 {public static void main (string[] args) {File origin = new File ("D:/helloworld.txt");
        File Destination = new file ("D:/helloworld6.txt");
        InputStreamReader in = null;
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        BufferedWriter writer = null;
            if (!origin.exists ()) {try {origin.createnewfile ();
            catch (IOException e) {e.printstacktrace (); } try {reader = new BufferedReader (new InputStreamReader FileInputStream (origin), ISO-8
859-1 "));
            reader = new BufferedReader (new FileReader (origin));
            writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (destination), "iso-8859-1"));
            String line = null;
  while (line = Reader.readline ())!=null) {writer.write (line);              Writer.newline ();
        } writer.flush ();
        catch (IOException e) {e.printstacktrace ();
                finally {if (in!=null) {try {in.close ();
                catch (IOException e) {e.printstacktrace ();
                } if (Out!=null) {try {out.close ();
                catch (IOException e) {e.printstacktrace ();
                } if (reader!= null) {try {reader.close ();
                catch (IOException e) {e.printstacktrace ();
                } if (Writer!=null) {try {writer.close ();
                catch (IOException e) {e.printstacktrace ();
 }
            }
        }
    }
}








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.