preface
Welcome to recommend and guide the review results of bloggers this week~~
What is Io? Is it classified like this? What classes are commonly used in java? What specific functions does it have? So let's focus on several issues. I hope you can understand IO through this blog and use it simply.
Initial IO flow
Several basic concepts we need to understand when learning IO
Files and folders
We all know that there are two forms of things in the computer, one is a file, the other is a folder. If we need to find it, we need a path
Then let's introduce some basic English words
- File: file
Is a data stream stored in a long-term storage device or temporary storage device
- Directory: folder / directory
Is used to store and organize documents
- path: path
The function of path in the program is to operate the corresponding file location, so we can't write the path dead to prevent errors
For example:
Path separator: semicolon in window and colon in linux
Name separator: backslash in window and forward slash in linux/
Let's look at an example of a standard path writing method: read the a.txt file on disk c
Principle and classification of IO stream
What is flow?
In programming, each language has a unique way of operating files, and java This way of inputting and outputting files is called streaming. Flow refers to a string of specific data flowing to a specified location through a specific channel.
It can be used to transfer files, pictures, audio, video and other data, or to transfer string files encoded into bytes.
The following is its classification:
- According to different data units
-Byte stream
-Output stream - Flow direction of data
-Output
-Input - According to the different roles of the flow
-Byte stream
-Processing flow / packaging flow
data source
We introduced some principles of flow earlier. Then we compare it to a water transmission process. Then it needs a water tank, which is the data source.
Common data sources include: database, disk file, network connection IO Equipment.
Characters and bytes
Let's first look at the definition in Baidu Encyclopedia
Characters refer to glyph like units or symbols, including letters, numbers, operation symbols, punctuation symbols and other symbols, as well as some functional symbols.
Byte is a unit of measurement used by computer information technology to measure storage capacity.
Here, I'm simply talking about my understanding. Characters are a unit that we can see, that is, the content that can be typed separately using the input method. For Chinese and English, it is a single character. The byte is the unit of the computer, which is composed of 0 and 1 at the bottom. 1 byte = 8 bits
Absolute path / relative path
FIle class
We learn a class from its construction method
Construction method
File creates a new file instance by converting the given path string into an abstract path.
-
Construction method I
File(String pathname)Parameters:
String pathname: the path name of the string
The path can end in a file or a folder
The path can be relative or absolute
Create a new File instance by converting the given path name into an abstract class path -
Construction method II
File(String parent ,String child)
In this construction method, the parameters can pass two paths, a parent class path and a child class path
So what are the benefits of writing like this?Parent and child paths can change dynamically
-
Construction method III
FIle(File parent, String child)
The parent abstract pathname and child pathname strings are used to create a new File instance
Common methods in file
Here are several common methods. Please go to javaAPI View in
Method of obtaining function
-
file.getAbsolutePath( )
Get the path in the file (if the absolute path is passed in, the absolute path is returned, and vice versa) -
file.getPath( )
Gets the path passed in the constructor -
file.getName( )
Gets the end of the file delivery path -
file.getLength( )
Get the file size, but cannot get the size of the folder (if the path of the folder is passed in, 0 will be returned at last)
Method of judging function
-
file.exists( )
This function is used very frequently. Its main function is to judge whether the incoming path exists and return a Boolean character -
file.isFile( )
Judge whether the path passed in the constructor ends with the file -
file.isDrectory( )
This method is to judge whether the path passed in the construction method ends in the form of a folder, which is mutually exclusive with the above methods
Create delete method
- file.createNewFile( )
This method is the same as its name. It is also a very common method to create a new file
It should be noted that this method will generate exceptions and need to be handled (exceptions will be generated if the path does not exist) - file.mkdirs( )
This method is used to create folders. We learned earlier that the word mkdirs means folders. Adding s means creating multi-level folders. Even if the path is passed in incorrectly, no exception will be thrown. If the method mkdirs does not add s, it means that only single-level folders can be created - file.delete( )
Delete the specified path in the constructor. The following two classes will not be deleted
- If there is something in the folder, it will not be deleted
- The path does not exist and will not be deleted
Note: delete is directly deleted from the disk. Use with caution
Common methods in java
- I nput stream
- InputStream (byte input stream)
InputStream byte input stream abstract class, which is the superclass of all class byte input streams
Let's introduce its use with a piece of code
@Test public void fillIn() { //Define file path String insrc = "/Users/liudemac/Desktop/word/test.txt"; //initialization FileInputStream fileInputStream = null; try { //The definition array accepts these contents byte[] b = new byte[1024]; //The integer number is defined here to get the parameters in the traversal process int i; fileInputStream = new FileInputStream(insrc); //It should be noted that if it returns - 1, it means that all characters have been taken out while ((i = fileInputStream.read(b)) != -1) { //We use iterator traversal to get the final result for (byte b1 : b) { System.out.print((char) b1); } } } catch (IOException e) { e.printStackTrace(); } finally { //Don't forget to close the resource at last if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) e.printStackTrace(); } } } }
In use, I have explained the usage of byte output stream InputStream in detail with code. It should also be noted that in order to improve the reading efficiency, I pass in an array in the read method.
InputStream There are three methods to read a stream, namely read(),read(byte[] b),read(byte[] b, int off, int len)
- Reader (character output stream)
The usage is similar to the last byte input stream, so I won't repeat it here.
Direct code
@Test public void fillIn() { String insrc = "/Users/liudemac/Desktop/word/test.txt"; FileReader fileReader = null; try { char[] b = new char[1024]; fileReader = new FileReader(insrc); fileReader.read(b); for (char b1 : b) { System.out.print( b1); } } catch (IOException e) { e.printStackTrace(); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
- O utput stream
- outputStream
This is the same as the upper byte input stream
The calling method is consistent with the above. I will directly talk about its implementation method writer
@Test public void fillOut() { String outsrc = "/Users/liudemac/Desktop/word/test.txt"; FileOutputStream fileOutputStream = null; try { //Pay attention to this character, which means whether to overwrite the previous writing. If this is not added, the contents of the previous file will be overwritten fileOutputStream = new FileOutputStream(outsrc,true); String str = "hello"; //The second and third parameters in parentheses indicate where to start and where to end fileOutputStream.write(str.getBytes(), 0, str.length()); } catch (IOException e) { e.printStackTrace(); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Buffered packing flow derived from node flow
Node flow?
Node flow is easy to understand, which is the example we cited in the methods commonly used in java above. They usually only target the read and write resources of specific data sources (as explained above).
That is, the implementation subclasses of various abstract classes called.
Column as we called above
Node flow knows, so what is wrapper flow? Let's look at a more official explanation
It can eliminate the implementation difference of node flow and provide convenient methods for input and output.
This sentence sounds confusing, but people familiar with java features know that this is a decorator pattern
Modifier mode
You can obtain objects in a dynamic and transparent way without affecting other objects
In this mode, a decoration class is created to wrap the original class and provide additional functions on the premise of maintaining the integrity of class methods.
It should be noted that this process completes the function addition by calling the wrapped object, rather than directly modifying the behavior of the object, which is equivalent to adding an intermediate layer.
So what's in the packaging stream Buffer Is to implement the method in the subclass, and then we call the method through the implementation class and directly pass in the parameters.
File copy
Finally, let's take a look at the practical application of IO. Let's copy something in one file and put it in another and file, which is called copy for short.
With the previous experience, I believe the partners will be able to write it quickly. I'll put the code here
@Test public void fileCopy() { String insrc = "/Users/liudemac/Desktop/word/text.txt"; String putsrc = "/Users/liudemac/Desktop/word/text1.txt"; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { byte[] b = new byte[1024]; int i; fileOutputStream = new FileOutputStream(insrc); fileInputStream = new FileInputStream(putsrc); while ((i = fileInputStream.read(b)) != -1) { //This output is used to print the read data to the console for viewing System.out.printf(new String(b, 0, i)); fileOutputStream.write(b, 0, b.length); } } catch ( IOException e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (fileOutputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }