Java Starter Series (10) Java IO

Source: Internet
Author: User

In general, there are two types of read and write operations in Java: character streams and byte flows .

What is a stream?

The flow is an abstract concept. When a Java program needs to read data from a data source, it opens a stream to the data source. The data source can be a file, memory, or network. Similarly, when a program needs to output data to a destination, it also opens a stream, and the data destination can be a file, memory, or network. The stream is created to handle the input and output of the data more easily.

So what's the difference between a byte stream and a character stream?

1. The byte stream is also called the raw data, which requires the user to read the code and convert it accordingly. The implementation of the character stream is based on automatic conversion, and the data is automatically converted into characters according to the JVM's default encoding when reading the data.

2. The character stream processing unit is a 2-byte Unicode character that operates on a character, character array, or string, and the byte stream processing unit is 1 bytes, manipulating bytes and byte arrays.

So the character stream is made up of characters that the Java Virtual machine converts bytes into 2-byte Unicode characters.

3. Byte stream can be used for any type of object, including binary objects, while character streams only handle characters or strings, byte stream provides the ability to handle any type of IO operation, but it cannot directly handle Unicode characters, and the character stream can be;

Based on the above differences, then under what circumstances use a character stream, under what circumstances with a word stream?

stream End is byte stream ,reader and writer end are character stream

The difference between the two is read and write, one is read by Byte, and the other is by character. The actual use is usually similar.

Reading and writing a file requires that the content be processed in rows , such as comparing specific characters, and a character stream is typically selected when processing a row of data.

Just read and write files, and the contents of the file independent, the general choice of byte stream.

If it is audio files, pictures, songs, it is better to use the word stream, if it is Chinese (text), with a character stream is preferable;

Say so much, the word stream and character stream processing files in the end how to use it?

Let's take a look at it. In Java, what are the steps to input and output operations?

1 opening a file using the file class

2 Specify the location of the output by a subclass of Byte stream or character stream

3 for read/write operations

4 off input/output

IO operation is a resource operation, always remember to close

Actual combat code

Read and write text files

 Packagecnki.common.test;;;;;;Importjava.util.ArrayList;ImportJava.util.Iterator;Importjava.util.List;;;Importorg.junit.Test; Public classTest {@Test Public voidFunction2 ()throwsIOException {File file=NewFile ("C:\\users\\wangzl\\desktop\\file\\file.txt"); List<String> list =NewArraylist<string>(); List.add ("Aaa1"); List.add ("BBB1"); List.add ("CCC1"); //Write by FileUtils (overwrite original text)Fileutils.writelines (file, "UTF-8", list); //Write by Ioutils (overwrite original text)Ioutils.writelines (list,NULL,Newfileoutputstream (file)); //AppendOutputStream OS =NewFileOutputStream (file,true);//The second argument, True, indicates an appendIoutils.writelines (list,NULL, OS, "UTF-8"); //read by FileUtilslist<string> lines_fileutils = fileutils.readlines (file, "UTF-8"); //read by Ioutilslist<string> lines_ioutils = Ioutils.readlines (NewFileInputStream (file), "UTF-8"); //TraverseIterator<string> it =Lines_fileutils.iterator ();  while(It.hasnext ()) {System.out.println ( ()); }} @Test Public voidfunction1 () {Try{File File=NewFile ("C:\\users\\wangzl\\desktop\\file\\file.txt"); List<String> list = fileutils.readlines (file, "UTF-8"); //method One: Super for loop traversal             for(String item:list) {System.out.println (item); }            //method Two: For the ArrayList speed is faster, with a for loop, the size of the conditional traversal:             for(inti = 0; I < list.size (); i++) {System.out.println (List.get (i)); }            //method Three: The general traversal of the collection class, from an earlier version, with an iterator iterationIterator<string> it =List.iterator ();  while(It.hasnext ()) {System.out.println ( ()); }        } Catch(IOException e) {e.printstacktrace (); }    }}
View Code

Recursively gets the files in the specified directory

    //recursively gets the files in the specified directory     Public voidgetallfilesbyrecursive (String path) {File file=NewFile (path); if(File.exists ()) {file[] files=File.listfiles (); if(Files.length = = 0) {System.out.println ("The folder is empty!"); return; } Else {                 for(File file2:files) {if(File2.isdirectory ()) {System.out.println ("Folder:" +File2.getabsolutepath ());                    Getallfilesbyrecursive (File2.getabsolutepath ()); } Else{System.out.println ("File:" +File2.getabsolutepath ()); }                }            }        } Else{System.out.println ("File does not exist!"); }    }
recursively gets the files in the specified directory



Java Starter Series (10) Java IO

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: 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.