Java Fundamentals Review of six-----IO streams

Source: Internet
Author: User

Objective

In the previous article, I reviewed the multithreading of Java. In this article, we mainly introduce the knowledge of Java IO .

Introduction to IO

What is IO?

The name of IO is also the abbreviation for input and output, which is the inputs and outputs stream. The input stream is used to read data from the source, and the output stream is used to write data to the target.

You can learn the IO stream from the following example diagram:

IO stream Usage

IO stream operations on files are mainly divided into character stream and byte stream.

character Stream

There are two abstract classes of character streams:Writer and Reader class.
Its corresponding subclass FileWriter and FileReader can realize the file read and write operation.
bufferedwriter and BufferedReader can provide buffer functions for increased efficiency.

I remember that in the early days of learning Java, character streams are used in the tutorials to read and write characters. It is common to run a Main method, then console input characters, get input characters to do some logic control and so on.
For example: Enter characters in the console, enter quit , enter other characters to print.

code example:

    public static void main(String[] args)  {        try {            test();        } catch (IOException e) {            e.printStackTrace();        }    }    private static void test() throws IOException {          String str;            // 使用 System.in 创建 BufferedReader             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));            System.out.println("输入字符, 输入 'quit' 退出。");            // 读取字符            do {               str=br.readLine();               System.out.println("您输入的字符是:"+str);            } while(!str.equals("quit"));             br.close();    }

Then we enter Hello and quit.
The results are as follows:

输入字符, 输入 'quit' 退出。hello您输入的字符是:hello您输入的字符是:quit您输入的字符是:quit

With the above example, we can easily understand the character stream.
In general, our main use of character stream is the case of read and write files, most of them are text files, such as the. txt suffix. Here we also introduce how to use.

code example:

    /**     *     * 写入和读取文件     * @throws IOException     */    private static void test2() throws IOException {        //创建要操作的文件路径和名称          String path ="E:/test/hello.txt";        String str="hello world";        FileWriter fw = new FileWriter(path);          fw.write(str);          fw.close();                  FileReader fr = new FileReader(path);          StringBuffer sb=new StringBuffer();        while(fr.ready()){            sb.append((char)fr.read());        }        System.out.println("输出:"+sb.toString());        fr.close();    }

Note: If you are running on a different system, you can use the file.separator method, which represents the system delimiter.

Output Result:

输出:hello word

In the code example above, we read and write to the file using the two classes FileWriter and FileReader , although it is possible to write and read a character, but it is not efficient because it is a direct read and write to the disk. In general, we use buffering for file reads and writes. The benefits of using buffering are like dumping garbage, sorting out the rubbish, and then dropping it on a certain scale, rather than having a bit of rubbish to pour it once.

Then add the bufferedwriter and BufferedReader classes in the code above to buffer them.

code example:

    /**     * 写入和读取文件     * @throws IOException     */    private static void test3() throws IOException {        //创建要操作的文件路径和名称          String path ="E:/test/hello.txt";        String str="你好!";        FileWriter fw = new FileWriter(path);          BufferedWriter bw=new BufferedWriter(fw);        bw.write(str);          bw.close();        fw.close();                  FileReader fr = new FileReader(path);          BufferedReader br=new BufferedReader(fr);        StringBuffer sb=new StringBuffer();        while(br.ready()){            sb.append((char)br.read());        }        System.out.println("输出:"+sb.toString());        br.close();        fr.close();    }

Note: You need to be aware of the order of closing, first close the buffer, and then close the file.

Byte stream

Byte stream also has two abstract classes:InputStream and outputstream classes.
The corresponding subclasses have FileInputStream and FileOutputStream to implement the file read and write operation.
bufferedinputstream and bufferedoutputstream provide buffer function

Byte stream can also read text, but its main use of the scene is to read the text information can not be directly obtained from the binary files, such as music files, video files, image files and so on.
Here we still read and write the file, but we write the contents of the previous write to the hello.txt file with ' Hello ' written to the new file. Because the Chinese is used here, the corresponding encoding needs to be set.

code example:

 /** * Create a file and read the record * @throws IOException */private static void Test4 () throws IOException {String        Path= "E:/test/hello.txt";        String path2= "e:/test/hello. txt";        String str= "Hello!";        Read data from a file InputStream input = new FileInputStream (path);        InputStreamReader reader = new InputStreamReader (input, "UTF-8");        StringBuffer sb=new StringBuffer ();        while (Reader.ready ()) {sb.append (char) reader.read ());        } input.close ();                Reader.close ();        Create a file and write data to the file OutputStream output = new FileOutputStream (path2);        OutputStreamWriter writer = new OutputStreamWriter (output, "UTF-8");                Writer.write (SB+STR);        Writer.close ();                Output.close ();        Read data from a file InputStream input2 = new FileInputStream (path2);        InputStreamReader reader2 = new InputStreamReader (input2, "UTF-8");        StringBuffer sb2=new StringBuffer (); while (readEr2.ready ()) {sb2.append (char) reader2.read ());        } System.out.println ("Output:" +SB2);        Input2.close ();    Reader2.close ();    }

Results:

    输出:hello world你好!

You can see that the results meet our expectations.

File

In the Learning IO stream, we also touch the File class.
The file class is primarily about manipulating folders. For example, folder creation, deletion, viewing, and so on.
Here we will briefly describe the relative use of the file class, or use the code with the comments to illustrate.

code example:

private static void test5() throws IOException {        String path="E:/test/test2";        String path2="E:/test/test3/test3";        String path3="E:/test/test2/test2.txt";        File f = new File(path);        File f2 = new File(path2);        File f3 = new File(path3);        //创建文件夹        System.out.println("="+f.mkdir());        //创建文件夹和所有父文件夹        System.out.println("=="+f2.mkdirs());        //创建一个文本        System.out.println("==="+f3.createNewFile());        //获取名称        System.out.println("==="+f3.getName());        //获取父级名称        System.out.println("==="+f3.getParent());        //获取当前路径        System.out.println("==="+f3.getPath());        //判断是否是目录        System.out.println("=="+f2.isDirectory());        System.out.println("==="+f3.isDirectory());        //删除该文件        System.out.println("==="+f3.delete());  }   

Output Result:

=true==true===true===test2.txt===E:\test\test2===E:\test\test2\test2.txt==true===false===true

The correlation of the file class is simply introduced, and the actual scenario needs to be configured for specific use. It is important to note that in the case of file creation and deletion, it is necessary to determine if there is any, otherwise an exception will be thrown.

Other

This is the end of this article, thank you for reading! Welcome message and praise, your support is my greatest motivation to write!

Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com

Java Fundamentals Review of six-----IO streams

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.