Advanced Io,properties of Java

Source: Internet
Author: User

Standard code for IO Stream (advanced) Release resources

The main consideration is when the release of resources is more appropriate. And before and after jdk1.7 is different.

Package Com.wzlove.demo;import Java.io.filereader;import Java.io.filewriter;import java.io.ioexception;/** * Standard IO format processing * * @author wzlove * @create 2018-07-23 9:54 */public class Standardio {//jdk7 before public static void main (string[] args)        {//initial assignment is null filereader FR = NULL;        FileWriter FW = NULL;            try {//Create character Stream Object FR = new FileReader ("Student.txt");            FW = new FileWriter ("Student.txt");            Manipulate resources (read-write, consume resources, as examples only) int len;            while (len = Fr.read ())! =-1) {fw.write (char) len);        }} catch (IOException e) {e.printstacktrace ();                    } finally {try {//To determine if the input stream is null if (fr! = null) {//close resource                Fr.close ();            }} catch (IOException e) {e.printstacktrace ();       } finally {try {//To determine if the input stream is null             if (fw! = NULL) {//close resource fw.close ();                }} catch (IOException e) {e.printstacktrace (); }}}}//Jdk7 after/** * Try (code to create IO stream object) {* Other code *}CATCH (Possible exception) {* Hit     Print exception Information *} * The above code automatically calls the Close method (that is, the IO stream object implements the Closeable interface (Closeable implements the Autocloseable interface), * overrides the Close method). Interested can view the source code  */public static void main (string[] args) {try (//Create character stream object FileReader fr = new                FileReader ("Student.txt");                FileWriter FW = new FileWriter ("Student.txt");                {//Operations resource (side-read-write, resource-consuming, as an example only) int len;                while (len = Fr.read ())! =-1) {fw.write (char) len);        }} catch (IOException e) {e.printstacktrace (); }    }}
Properties

is a subclass of map (meaning that it has all of the map). The type of the key and value for this class are string types,
The properties used in development will operate on the file in conjunction with IO streams,

A special method:

    • String getProperties (String key): Gets the corresponding value according to the key
    • Object setproperties (String key,string value): Adds a key-value pair mapping relationship to the collection, and the return value is the value that is replaced.

Persist the data in the Properties object (write data to a file):

    • void Store (OutputStream out, String comments): Writes the contents of the properties object to the specified file using a byte stream,
      Comments means a description of the data in the file.
    • void Store (writer writer, String comments): Writes the contents of the properties object to the specified file using a character stream,
      Comments means a description of the data in the file.

Get data from a file into the Properties collection

  • void load (InputStream instream): Writes the contents of a file in a byte stream to the Properties object.
  • void load (Reader reader): Writes the contents of a file in a character stream to an object in properties.

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

          Create property Set object Properties P = new properties ();      Add Data/*p.put ("001", "Dilly Hot Bar");      P.put ("002", "Zhengshuang");      P.put ("003", "Michelle Yeoh"); *//Call method, write File//P.store (New FileWriter ("A.properties"), "test file");      P.store (New FileWriter ("A.txt"), "test file");      P.store (New FileOutputStream ("B.properties"), "test file");      Call the method and read the file/*p.load (new FileReader ("A.properties"));      The sub-class of map, traverse the method and map as Set<map.entry<object, object>> entries = P.entryset (); For (Map.entry<object, object> entry:entries) {System.out.println (Entry.getkey () + "=" + Entry.getvalue (      ));      }*/P.load (New FileInputStream ("B.properties"));      The sub-class of map, traverse the method and map as Set<map.entry<object, object>> entries = P.entryset ();      Iterator<map.entry<object, object>> Iterator = Entries.iterator ();          while (Iterator.hasnext ()) {map.entry<object, object> Map = Iterator.next (); System.out.println (Map.getkeY () + "=" + Map.getvalue ()); }  }
Efficient flow
    • Efficient byte stream:
      1. Efficient byte input stream (Bufferedinputstream)
      2. Efficient byte output stream (Bufferedoutstream)
    • Efficient character stream:
      1. efficient character input stream (BufferedReader)
      2. Efficient character output stream (BufferedWriter)
Efficient byte stream

Construction Method:

    • Public Bufferedinputstream (InputStream in): Creates a new buffered input stream.
    • Public Bufferedoutputstream (OutputStream out): Creates a new buffered output stream.

Common methods:
The method is not different from the normal byte stream method. Here's an example to test the efficiency of two, the file size is more than 70 trillion

public static void Main (string[] args) throws IOException {//Bufferedcopy (); Bytecopy ();}    public static void Bufferedcopy () throws IOException {Long startTime = System.currenttimemillis (); Bufferedinputstream bis = new Bufferedinputstream (New FileInputStream ("f:\\desktop\\desktop\day09\\day09\\avi\\01-    Today's content. Itcast "));    Bufferedoutputstream BOS = new Bufferedoutputstream (New FileOutputStream ("Abc.avi"));    int Len;    while (len = Bis.read ())! =-1) {bos.write (len);    } bos.close ();    Bis.close (); System.out.println (System.currenttimemillis ()-startTime);    3171}public static void Bytecopy () throws IOException {Long startTime = System.currenttimemillis ();    FileInputStream fis = new FileInputStream ("F:\\desktop\\desktop\\day09\\day09\\avi\\01-today's content. Itcast");    FileOutputStream fos = new FileOutputStream ("Bcd.avi");    int Len;    while (len = Fis.read ())! =-1) {fos.write (len);    } fis.close ();    Fos.close (); System.out.println (System. Currenttimemillis ()-startTime); 297409}
Character Efficient Flow

Construction Method:

    • Public BufferedReader (Reader in): Creates a new buffered input stream.
    • Public BufferedWriter (Writer out): Creates a new buffered output stream.

Common methods (the parent class has it all):

    • void NewLine (): (a method of efficiently outputting character streams) writes out a line break, cross-platform.
    • String ReadLine (): reads a row of data (the end flag is null)

      Package com.wzlove.buffered;

      Import java.io.*;
      Import Java.util.Scanner;

      /**
      • Test efficient character streams
      • @author Wzlove
      • @create 2018-07-23 15:32
        */
        public class Demo1 {

        public static void Main (string[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter (New FileWriter ("C.txt"));
        Scanner in = new Scanner (system.in);
        String str;
        while (true) {
        System.out.println ("Please enter what you want:");
        str = In.nextline ();
        if (Str.equals ("ends")) {
        Break
        }
        Bw.write (str);
        Bw.newline ();
        }
        Bw.flush ();
        Bw.close ();

         System.out.println("您输入的内容是:"); BufferedReader br = new BufferedReader(new FileReader("c.txt")); String str2; while((str2 = br.readLine()) != null){     System.out.println(str2); } br.close();

        }
        }

Convert stream (character stream)
    • InputStreamReader
      1. Construction method
        1. InputStreamReader (InputStream in): Creates a character stream that uses the default character set.
        2. InputStreamReader (InputStream in, String CharsetName): Creates a character stream of a specified character set.
      2. Common methods
        1. int read () reads one character
        2. void Close () closes the stream and frees any system resources associated with it.
    • OutputStreamWriter
      1. Construction method
        1. OutputStreamWriter (OutputStream in): Creates a character stream that uses the default character set.
        2. OutputStreamWriter (OutputStream in, String CharsetName): Creates a character stream of a specified character set.
      2. Common methods:
        1. void Close () closes the stream and refreshes first.
        2. void Flush () flushes the stream.
        3. void write (int c) writes a character
        4. void write (String str) writes a string

When do I use it? If you need to read and write data in the specified character set.

    Package com.wzlove.demo1;    Import java.io.*;        Import Java.util.Scanner;  /** * Test Conversion stream * @author Wzlove * @create 2018-07-23 18:20 */public class Demo {public static  void Main (string[] args) throws IOException {//create efficient output stream bufferedwriter bw = new BufferedWriter (new                OutputStreamWriter (New FileOutputStream ("D.txt"), "GBK"));            Write data Scanner in = new Scanner (system.in);                while (true) {System.out.println ("Please output content");                String str = in.nextline ();                if (Str.equals ("ends")) {break;                } bw.write (str);            Bw.newline ();            } in.close ();            Close flow Bw.flush ();                Bw.close ();            Create an efficient input stream bufferedreader br = new BufferedReader (new InputStreamReader (New FileInputStream ("D.txt"), "GBK"));            String str; while (str =Br.readline ()) = null) {System.out.println (str);        } br.close (); }    }

Memory learned IO stream:

字节:    InputStream        |-- FileInputStream : 输入字节流        |-- FilterInputStream (不用管,没学)            |-- BufferedInputStream : 高效缓冲输入字节流    OutputStream        |-- FileOutputStream : 输出字符流        |-- FilterOutputStream (不用管,没学)            |-- BufferedOutputStream : 高效缓冲输出字节流字符:          Reader        |-- BufferedReader : 高效缓冲字符输入流        |-- InputStreamReader : 转换流,从字节流到字符流的桥            |-- FileReader : 字符输入流    Writer        |-- BufferedWriter : 高效缓冲字符输出流        |-- OutputStreamWriter : 转换流,是字符的桥梁流以字节流            |-- FileWriter : 字符输出流

Advanced Io,properties of Java

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.