Io stream in Java, overview and summary of input and output streams

Source: Internet
Author: User
Tags closing tag readable

Transferred from: https://www.cnblogs.com/biehongli/p/6074713.html

The 1:java language defines many classes that are specifically responsible for input or output in various ways, and these classes are placed in the java.io package. which

All input stream classes are abstract class InputStream (byte input stream), or abstract class reader (character input stream) subclass;

All output streams are subclasses of the abstract class OutputStream (byte output stream) or writer (character output stream).

The first thing to understand is: what is the flow??? (For permanent data retention)

The input stream and output stream are divided according to the different data flow.

According to the different types of processing data are divided into character stream and byte stream;

"Then you need to understand that the input mode and the output mode are who flows to who:

InputStream (byte input stream) and reader (character input stream) The popular understanding is read.

OutputStream (byte output stream) and writer (character output stream) The popular understanding is written (writer).

Finally, the following figure out the type of various types of how to use, who contains who, to clarify the idea.

The 2:inputstream class is the abstract class of the byte input stream, which is the parent class of all byte input streams, and the InputStream class has a hierarchy as shown;

The characters in the 3:java are Unicode encoded and are double-byte. InputStream is used to process bytes, which is inconvenient when dealing with word literals. Java provides a specialized set of reader types for the input of character literals. The reader class is an abstract class of character input streams, and the implementation of all character input streams is its subclass.

4: Output stream The OutputStream class is an abstract class of byte input streams that represents the superclass of all classes that output a stream of bytes.

The 5:writer class is an abstract class of character output streams, and the implementation of all character output classes is its subclass.

The 6:file class is the only object in the IO package that represents the disk file itself. Create, delete, and rename files through file. The main function of the file class object is to get some information about the text itself. such as the directory where the text resides, the length of the file, read and write permissions, and so on. (Some need memory, such as Isfile (), isdirectory (), exits (); View API when used)

details are as follows: File Class (Overview and construction method of the file class) Overview of the A:file class file should also be called a path file path or folder path path is divided into absolute path and relative path an absolute path is a fixed path, starting with the drive letter relative path relative to a location, under Eclipse, under current project, under DOS The View API refers to the current path Abstract representation of file and directory path names B: Construction Method file (String pathname): Gets the file object based on a path file (string parent, String child): Gets the file object based on a directory and a sub-file/directory file (file parent, String child): Gets the file object based on a parent file object and a sub-file/directory File class (the creation function of the file class) A: Create A feature Public Boolean CreateNewFile (): Create file If such a file exists, you do not create a Public Boolean mkdir (): Create folder if such a folder exists, you do not create a Public Boolean mkdirs (): Create a folder, if the parent folder does not exist, will help you create it (using the CreateNewFile () file created without a. txt or other suffix is also a file, not a folder, using MkDir () to create a folder, if the name is such as Aaa.txt is also a folder is not a file;) Precautions : If you create a file or folder and forget to write the drive path, the default is under Project path.   file Class (rename and delete function for file class) A: Renaming and deleting features Public boolean Renameto (file dest): Renames the file to the specified file path Public Boolean Delete (): Delete file or folder B: Renaming Considerations if the path name is the same, it is renamed. if the path name is different, it is renamed and clipped. C: Removal precautions: Delete in Java does not go to the Recycle Bin. to delete a folder, note that the folder cannot contain files or folders   File Class (The judgment function of the file class) A: Judging function Public Boolean isdirectory (): Determines whether the directory Public Boolean isfile (): Determines whether the file is Public Boolean exists (): Determine if there is Public Boolean CanRead (): Determines whether it is readable Public Boolean canWrite (): Determines if writable Public Boolean Ishidden (): Determines whether to hide

file Class (Get function of file class) A: Get features Public String GetAbsolutePath (): Gets the absolute path Public String GetPath (): Get Path Public String GetName (): Get name Public long Length (): Gets the length. Number of bytes Public Long LastModified (): Gets the last modified time, millisecond value Public string[] list (): Gets an array of names for all files or folders under the specified directory Public file[] Listfiles (): Gets the file array of all files or folders under the specified directory File Class (an overview and use of the name filter) A: Overview of file name Filters Public string[] List (filenamefilter filter) Public file[] Listfiles (filefilter filter)
 1 package Com.ningmeng; 2 3 Import Java.io.File; 4 5 public class Test {6 7 public static void Main (string[] args) throws exception{8//TODO Auto-generate D Method stub 9 File File=new file ("Aa.txt");//file is created by default under the project you created, refresh to see the System.out.println (File.exists ()) ;//Determine if the file exists one by one file.createnewfile ();//Create a file, not a folder System.out.println (File.exists ());//Determine again if there is a Ystem.out.println (File.getname ());//Gets the name of the file System.out.println (File.getabsolutepath ());//Gets the absolute path to the file, Sys Tem.out.println (File.getpath ());//Gets the relative path of the file System.out.println (File.getparent ());//Gets the file's parent path, System.out . println (File.canread ());//Whether the file is readable System.out.println (File.canwrite ());//Whether the file is writable System.out.println . Length ());//File Length System.out.println (file.lastmodified ());//File Last modified by SYSTEM.OUT.PRINTLN (File.isdir Ectory ());//Determine if the file is a directory of System.out.println (File.ishidden ());//Whether the file hides the System. Out.println (File.isfile ());//Determine if the file exists 24}25 26} 

Public string[] List (): Gets an array of names for all files or folders under the specified directory

Public file[] Listfiles (): Gets the file array of all files or folders under the specified directory

List () gets all the files or folders in a directory:

1 package Com.ningmeng; 2  3 import java.io.File; 4  5 public class Filetest {6  7 public     static void Main (string[] args) {8         Fi Le file=new file ("d:/");//Specify Files directory 9         string[] str=file.list ();//Get an array of names for all files or folders under the specified directory         (String s:str) { Enhanced for loop traversal output one             System.out.println (s);         }13     }15}
1 package Com.ningmeng; 2  3 import java.io.File; 4  5 public class Filetest {6  7 public     static void Main (string[] args) {8         Fil E file=new file ("d:/");//Specify the path 9         file[] F=file.listfiles ();//Gets the file array for all files or folders under the specified directory         (file fi:f) {// Enhanced for loop traversal output one             System.out.println (FI);         }13     }15}

Case Demo:

Get a file in a format such as getting a picture of a suffix and outputting the file name:

1 package Com.ningmeng; 2  3 import java.io.File; 4  5 public class Filetest {6  7 public     static void Main (string[] args) {8         Fil E file=new file ("C:\\users\\biehongli\\pictures\\xuniji"); 9         string[] Str=file.list (), ten         for         (String s:str) {             if (S.endswith (". jpg") | | s.endswith (". png")) {//If the suffix is in this format, the output                 is System.out.println (s);             }15         }16     }19}

The following shows the Get folder under the face directory of the file gets (and did not fully get subdirectories subdirectory and so on, just get the sub-level directory):

1 package Com.ningmeng; 2  3 import java.io.File; 4  5 public class Filetest {6  7 public     static void Main (string[] args) {8         Fil E file=new file ("C:\\users\\biehongli\\pictures\\camera roll"); 9         file[] F=file.listfiles (), one for         (File fi:f) {14             if (Fi.isdirectory ()) {//judgment if it is a directory                 string[] S=fi.list (); (                 String str:s) {                     if (Str.endswith (". jpg")) {                         System.out.println (str);                     }19                 }20             }21         }22     }23}

A: Overview of file name filters

Public string[] List (filenamefilter filter) Public file[] Listfiles (filefilter filter)
1 package Com.ningmeng; 2  3 import java.io.File; 4 import java.io.FilenameFilter; 5  6 public class Filetest {7  8 public     static VO ID Main (string[] args) {9         file File=new file ("C:\\users\\biehongli\\pictures\\camera roll");         [] Str=file.list (New FilenameFilter () {//filter, anonymous internal class @Override14 public             Boolean accept (file dir, String name) {                 //TODO auto-generated method Stub16                 //system.out.println (dir);//Get the path of the file                 SYSTEM.OUT.PRINTLN (name);//Get the name of the file                 f=new files (dir,name),                 return F.isfile () && f.getname ( ). EndsWith (". jpg");             }21         });         (String s:str) {             System.out.println (s);         }25         +     } 27}

7: Below with some bytes of input and output stream specific case operations (when the operation of the time to recognize that you are using a byte stream or a character stream):

Note: The Read () method reads a byte and why it is returned as an int instead of a byte byte input stream can manipulate any type of file, compared to chip audio, these files are stored in binary form, if each read return byte, it is possible to read in the middle of the time encountered 111111111; then this 11111111 is byte type-1, Our program is encountered 1 will stop not reading, the latter data is not read, so at the time of reading with the int type received, if 11111111 will be in front of it, 24 0 to fill 4 bytes, Then 1 of the byte type becomes 255 of the int type, which guarantees that the entire data is read, and that -1 of the closing tag is the int type

FileInputStream Single byte reads:

FileOutputStream a single byte write:

1 package Com.ningmeng; 2  3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5  6 public class Filetest {7  8     PU Blic static void Main (string[] args) throws exception{9         fileinputstream fis=new fileinputstream ("Aaa.txt");         FileOutputStream fos=new FileOutputStream ("Bbb.txt", true); one         //fileoutputstream () followed by true refers to a file appended with         13         int A=fis.read ();//read () reads one byte         at a time System.out.println (a);//read a byte output of         Fos.write (101);//write () write one byte at a time         fis.close ();//must remember to close the stream, Develop a good habit of         fos.close ();     }20}

FileInputStream and fileoutputstream to copy text or pictures or songs:

1 package Com.ningmeng; 2  3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5  6 public class Filetest {7  8     PU Blic static void Main (string[] args) throws exception{9         fileinputstream fis=new fileinputstream ("Aaa.txt");         FileOutputStream fos=new FileOutputStream ("Bbb.txt");         if there is no bbb.txt, it creates an         int b;14 while         ( (B=fis.read ())!=-1) {             fos.write (b);         }17         fis.close (); Fos.close ()         ;     }20}

FileInputStream and FileOutputStream define decimal groups for read and write operations:

1 package Com.ningmeng; 2  3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5  6 public class Filetest {7  8     PU Blic static void Main (string[] args) throws exception{9         fileinputstream fis = new FileInputStream ("Aaa.txt");         FileOutputStream fos = new FileOutputStream ("Bbb.txt");         int len;12         byte[] arr = new byte[1024 * 8];//custom byte array 13< c8/>14 while         (len = Fis.read (arr))! =-1) {             //fos.write (arr);             fos.write (arr, 0, Len);// Write out the byte array write valid bytes number         }18         //io stream (definition decimal group)         //write (byte[] b)         //write (byte[] b, int off, int len) Write a valid number of bytes         fis.close ();         fos.close ();     }25}

io Stream (bufferedinputstream and bufferoutputstream copies)

* A: Buffering ideas * Byte stream reading and writing an array at a time is significantly faster than reading and writing one byte at a time, * This is a buffer effect added to the array, Java itself at the time of design, * This design idea is also taken into account, so the byte buffer stream is provided * B.bufferedinputstream * Bufferedinputstream built in a buffer (array) * When reading a byte from the Bufferedinputstream * Bufferedinputstream will be read from the file 8,192, in the buffer, returned to the program a * When the program is read again, it will not need to find the file, directly from the buffer to get * until all of the buffers have been used before they are read back from the file by 8,192 * C.bufferedoutputstream * Bufferedoutputstream also has a built-in buffer (array) * When the program writes out bytes to the stream, it is not written directly to the file and is written to the buffer * Until the buffer is full, Bufferedoutputstream writes the data in the buffer once to the file.
1 package Com.ningmeng; 2  3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.FileInputStream; 6 Import Java.io.FileOutputStream; 7  8 public class Filetest {9     , public static void main (string[] args) throws exception{11         FileInputStream fi s = new FileInputStream ("Aaa.txt"),         fileoutputstream fos = new FileOutputStream ("Bbb.txt");         Bufferedinputstream bis=new bufferedinputstream (FIS);/         /Use decorative mode to decorate the FIS into the BIS. Use buffered read speed to         bufferedoutputstream bos=new bufferedoutputstream (FOS), +         int b;19 while         (b= Bis.read ())!=-1) {             bos.write (b);         }22         bis.close (); Bos.close         ();     }25}

face question : which is faster to read and write to the decimal group and to fetch with buffered?

* Define a decimal group if it is 8,192 byte size and buffered comparison * Defining decimal groups is notch above because the same array of read and write operations * While the buffered operation is two arrays io Stream (difference between flush and close methods) Flush () method: used to flush the buffer, after the refresh can be written again (byte buffer stream built-in buffer, if not read out, you can use Flush () flush) the Close () method: The Close () method of the Stream object that is used to shut down the stream, if it is a flow with a buffer, not only closes the stream, but also flushes the buffer before closing the stream, and can no longer write 8: Character stream FileReader and FileWriter what is a character stream? * Character stream is an IO stream that can read and write characters directly * Character stream to read characters, first read to the byte data, and then to the character. If you want to write characters, you need to convert the characters to bytes and write them out. IO Stream (in which case a character stream is used) * Character stream can also copy text files, but not recommended. Because the byte is converted to a character when it is read, and the character is returned to the byte when it is written. * The program needs to read a piece of text, or need to write a piece of text when you can use a character stream * Read by the size of the characters are read, will not appear half Chinese * You can write the string directly, without converting it to a byte array. IO Stream (whether the character stream can copy non-plain text files) * Non-plain text files cannot be copied * Because the byte is converted to a character while reading, the corresponding character may not be found during the conversion, and the character will be converted into bytes when written. * If it is, write directly, so that the file after writing is messy, can not see
1 package Com.ningmeng; 2  3 import java.io.FileReader; 4 import java.io.FileWriter; 5  6 public class Filetest {7  8 public     static void Main (string[] args) throws exception{9         //filereader class's Read () method can be read by the character size of the FileReader fr=new FileReader         ( "Aaa.txt");         int b;12 while         ((B=fr.read ())!=-1) {System.out.println             ((char) b);//int type to character         fr.close ();         The Write () method of the//filewriter class can automatically convert a character to a byte and write         the FileWriter fw = new FileWriter (" Aaa.txt ", true);         fw.write (" AAA ");         fw.close ();         copy of the character stream         FileReader FR2 = new FileReader ("Aaa.txt"),         FileWriter fw2 = new FileWriter ("Bbb.txt"), +         int ch;27 while         (ch = Fr2.read ())! =-1) {             fw2.write (ch);         }30         fr2.close ();         fw2.close ();}34     }
1 package Com.ningmeng; 2  3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.FileReader; 6 import Java.io.Fil Ewriter; 7  8 public class Filetest {9     , public static void main (string[] args) throws exception{11         BufferedReader br= New BufferedReader (New FileReader ("Aaa.txt")),         bufferedwriter bw=new bufferedwriter (New FileWriter ("Bbb.txt") )         ///BufferedReader and BufferedWriter use: +         int b;15 while         ((B=br.read ())!=-1) {             Bw.write ((char) b);         }18         br.close ();         bw.close ();     }21}

First write here, the content is more, after the time to summarize, but also to facilitate their own brain repair 

Io stream in Java, overview and summary of input and output 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.