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

Source: Internet
Author: User

The summary is very rough, the later time is rich to revise a bit well.

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 classfile should also be called a pathfile path or folder pathpath is divided into absolute path and relative pathan absolute path is a fixed path, starting with the drive letterrelative path relative to a location, under Eclipse, under current project, under DOSThe View API refers to the current pathAbstract representation of file and directory path namesB: Construction Methodfile (String pathname): Gets the file object based on a pathfile (string parent, String child): Gets the file object based on a directory and a sub-file/directoryfile (file parent, String child): Gets the file object based on a parent file object and a sub-file/directoryFile class (the creation function of the file class)A: Create A featurePublic Boolean CreateNewFile (): Create file If such a file exists, you do not create aPublic Boolean mkdir (): Create folder if such a folder exists, you do not create aPublic 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 featuresPublic boolean Renameto (file dest): Renames the file to the specified file pathPublic Boolean Delete (): Delete file or folderB: Renaming Considerationsif 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 functionPublic Boolean isdirectory (): Determines whether the directoryPublic Boolean isfile (): Determines whether the file isPublic Boolean exists (): Determine if there isPublic Boolean CanRead (): Determines whether it is readablePublic Boolean canWrite (): Determines if writablePublic Boolean Ishidden (): Determines whether to hide

file Class (Get function of file class)A: Get featuresPublic String GetAbsolutePath (): Gets the absolute pathPublic String GetPath (): Get PathPublic String GetName (): Get namePublic long Length (): Gets the length. Number of bytesPublic Long LastModified (): Gets the last modified time, millisecond valuePublic string[] list (): Gets an array of names for all files or folders under the specified directoryPublic file[] Listfiles (): Gets the file array of all files or folders under the specified directoryFile Class (an overview and use of the name filter)A: Overview of file name FiltersPublic string[] List (filenamefilter filter)Public file[] Listfiles (filefilter filter)
1 packageCom.ningmeng; 2 3 ImportJava.io.File; 4 5 public classTest {6 7 public static void Main (string[] args) throws exception{8//TODO auto-generated Method stub 9 File File=new file ("Aa.txt");//file is created by default under the project you created, swipe New can see the System.out.println (File.exists ());//Determine whether the file exists one by one file.createnewfile ();//create file, not folder System. Out.println (File.exists ());//re-determine the existence of the SYSTEM.OUT.PRINTLN (File.getname ());//Get the name of the file System.out.println ( File.getabsolutepath ());//Gets the absolute path of the file System.out.println (File.getpath ());//Gets the relative path of the file by System.out.println ( File.getparent ());//Gets the parent path of the file System.out.println (File.canread ());//Whether the file is readable System.out.println (FILE.CANWR ITE ());//Whether the file can be written in System.out.println (File.length ());//File length of System.out.println (File.lastmodified ());//File The last modified time is System.out.println (File.isdirectory ());//Determine whether the file is a directory of System.out.println (File.ishidden ());//Text System.out.println (File.isfile ());//Determine if the file exists in }25  

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     St atic void Main (string[] args) {8 file         file=new file ("d:/");//Specify Directory 9         string[] str=file.list ();// Gets an array of names for all files or folders under the specified directory.                      }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 file         file=new file ("d:/");//Specify Path 9         file[] F=file.listfiles ();// Gets the file array of all files or folders under the specified directory.                      }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         file File=new file ("C:\\users\\biehongli\\pictures\\xuniji"); 9         string[ ] str=file.list (); Ten for }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         file File=new file ("C:\\users\\biehongli\\pictures\\camera roll"); 9         10< C11/>file[] f=file.listfiles ();one for (File fi:f) {if (Fi.isdirectory ()) {///Judging if it is a directory string[] s=  Fi.list (); (String str:s) {if (Str.endswith (". jpg" }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 void
        main (string[] args) {9         file File=new file ("c:\\users\\biehongli\\ Pictures\\camera Roll ' @Override14 public boolean Accept (File dir, String name) {//TODO auto-generated Metho D stub16//system.out.println (dir);//Gets the path of the file//system.out.println (name);//Gets the name of the file F=new files (dir,name) ; return F.isfile () && f.getname (). EndsWith (". jpg" })  ;    
      

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 bytebyte 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 public     static void Main (string[] args) throws exception{9         Fileinputstrea M fis=new fileinputstream ("Aaa.txt"); FileOutputStream fos=new FileOutputStream ("Bbb.txt", True }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 public     static void Main (string[] args) throws exception{9         Fileinputstrea M fis=new fileinputstream ("Aaa.txt"); FileOutputStream fos=new FileOutputStream ("Bbb.txt"); 11// If there is no bbb.txt, an int b;14 while ((B=fis.read ())!=-1 }20}  is created     

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 public     static void Main (string[] args) throws exception{9         Fileinputstrea M FIS = new FileInputStream ("Aaa.txt"), FileOutputStream fos = new FileOutputStream ("Bbb.txt"); int Le N;12 byte[] arr = new byte[1024 * 8];//custom byte array (len = Fis.read (arr))! =-1 }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 Publ IC static void Main (string[] args) throws exception{11 fileinputstream fis = new FileInputStream ("Aaa.txt"); Fil Eoutputstream fos = new FileOutputStream ("Bbb.txt"); Bufferedinputstream bis=new Bufferedinputstream ( FIS); 15//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 }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 arraysio 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 write8: Character stream FileReader and FileWriterwhat 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  File Test {7 8 public static void Main (string[] args) throws  exception{9//filereader class's Read () method can be read by character size 1 0 FileReader fr=new filereader ("Aaa.txt" ); int  b;12 while ((B=fr.read ())!=-1 ) {System.out.pri Ntln (char) b);//int type to character }15  fr.close (); the Write () method of the//filewriter class can automatically convert characters to bytes write-up FileWriter FW = New FileWriter ("Aaa.txt", True ), Fw.write ("AAA" ),  fw.close (), 21 22//copy of character stream FileReader FR2 = new FileReader ("Aaa.txt" ), FileWriter fw2 = new FileWriter ("Bbb.txt" ), + int  ch;27 while (ch = fr2.rea D ())! =-1 ) {fw2.write  (ch),}34 }30  fr2.close ();  fw2.close (); > 
1 package Com.ningmeng; 2  3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 Import  Java.io.FileReader; 6 import Java.io.FileWriter; 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")),use of//BufferedReader and BufferedWriter: +int b;15 while ((B=br.read ())!=-1) {bw.write (char }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.