当前位置:网站首页>Chapter 13 IO flow
Chapter 13 IO flow
2022-07-27 12:14:00 【Haha's tea】
Catalog
1. Character stream FileReader and FileWriter Use
2. Byte stream FileInputStream and FileOutputStream Use
3. One of the processing streams : The use of buffer streams
4. Treatment flow 2 : The use of conversion streams
5. Standard input 、 Output stream
6. Print stream :PrintStream and PrintWriter
Custom classes implement serialization and deserialization operations
10. NIO.2 in Path、Paths、Files The use of the class
File The use of the class
1.File An object of class , Represents a file or a file directory ( Be commonly called : Folder )
2.File Class declaration in java.io It's a bag
3.File Class involves the creation of files or file directories 、 Delete 、 rename 、 Modification time 、 File size, etc , It does not involve writing or reading the contents of the file . If you need to read or write the contents of the file , You have to use IO Flow to complete .
4. follow-up File The object of the class is often passed as an argument to the constructor of the stream , To indicate read or write to “ End ”

1. How to create File Class
File(String filePath)
File(String parentPath,String childPath)
File(File parentFile,String childPath)2. Relative paths : Compared with the path indicated under a certain path . Absolute path : The path to the file or file directory that contains the drive letter

3. Path separator : windows:\\ unix:/
Common methods
public String getAbsolutePath(): Get absolute path
public String getPath(): Get path
public String getName(): Get the name
public String getParent(): Get the upper file directory path . If there is no , return null
public long length(): Get file length ( namely : Number of bytes ). Cannot get the length of the directory .
public long lastModified(): Get the last modification time , Millisecond value
The following method applies to file directories :
public String[] list(): Get the name array of all files or file directories in the specified directory
public File[] listFiles(): Get all the files in the specified directory or file directory File Array
public boolean renameTo(File dest): Rename the file to the specified file path
such as :file1.renameTo(file2) For example
To ensure return true, need file1 It exists in the hard disk , And file2 Can't exist in the hard disk .
public boolean isDirectory(): Determine whether it is a file directory
public boolean isFile(): Determine if it's a document
public boolean exists(): Judge whether it exists
public boolean canRead(): Judge whether it is readable
public boolean canWrite(): Judge whether it is writable
public boolean isHidden(): Determine whether to hide
Create the corresponding file or file directory in the hard disk
public boolean createNewFile(): create a file . If the file exists , Do not create , return false.
public boolean mkdir(): Create file directory . If this file directory exists , We won't create . If the upper directory of this file directory does not exist , It doesn't create .
public boolean mkdirs(): Create file directory . If the upper file directory does not exist , Exist together
Delete a file or file directory from the disk
public boolean delete(): Delete files or folders
Delete notes :java Delete in does not go to the recycle bin . To delete successfully ,io4 There can't be subdirectories or files in the file directory I/O yes Input/Output Abbreviation ,I/O Technology is a very practical technology , be used for Data transmission between processing devices . As read / Writing documents , Network communication, etc .Java In the program , For data input / Output operation to “ flow (Stream)” By .java.io A variety of “ flow ” Classes and interfaces , To get different kinds of data , And pass Standard method Input or output data .
One 、 Classification of flows
1. Operating data units : Byte stream 、 Character stream
2. The flow of data : Input stream 、 Output stream
3. The role of flow : Node flow 、 Processing flow

Two 、 Flow architecture
Abstract base class Node flow ( Stream or file ) Buffer flow ( One kind of processing flow )
InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer))
OutputStream FileOutputStream (write(byte[] buffer,0,len)) BufferedOutputStream (write(byte[] buffer,0,len)) / flush()
Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine())
Writer FileWriter (write(char[] cbuf,0,len)) BufferedWriter (write(char[] cbuf,0,len)) / flush()1. Character stream FileReader and FileWriter Use
take day09 Under the hello.txt The contents of the file are read into the program , And output to the console
explain : 1.read(): Returns a character read in . If the end of the file is reached , return -1 read(char[] cbuf): Return every read in cbuf The number of characters in the array . If the end of the file is reached , return -1
2. Exception handling : In order to ensure that the stream resource can be closed . Need to use try-catch-finally Handle
3. The file read in must exist , Otherwise it will be reported FileNotFoundException.
Write data from memory to a file on the hard disk
explain :1. Output operation , Corresponding File Can not exist . No exception will be reported
2. File If the file in the corresponding hard disk does not exist , In the process of output , This file will be created automatically .
File If the file in the corresponding hard disk exists :
If the constructor used by the stream is :FileWriter(file,false) / FileWriter(file): Overwrite the original file
If the constructor used by the stream is :FileWriter(file,true): The original file will not be overwritten , Instead, the contents are added on the basis of the original documents
2. Byte stream FileInputStream and FileOutputStream Use
Conclusion :1. For text files (.txt, .java, .c, .cpp), Use character stream FileReader、FileWriter Handle
2. For non text files (.jpg, .mp3, .mp4, .avi, .doc, .ppt, ...), Use byte stream FileInputStream、FileOutputStream Handle
3. One of the processing streams : The use of buffer streams
1. Buffer flow :BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
2. effect : Improve the read speed of the stream 、 The speed of writing The reason to improve the speed of reading and writing : Internally, a buffer is provided , By default 8kb
3. Processing flow , Namely “ Socket joint ” On the basis of existing flows .
explain : While closing the outer laminar flow , The inner layer flow will be automatically closed . Therefore, the closing of inner laminar flow can be omitted .
4. Treatment flow 2 : The use of conversion streams
1. Converted flow : Belongs to the character stream
InputStreamReader: Convert a byte input stream to a character input stream
OutputStreamWriter: Convert the output stream of one character to the output stream of bytes 2. effect : Provides conversion between byte stream and character stream
3. decode : byte 、 Byte array ---> A character array 、 character string code : A character array 、 character string ---> byte 、 Byte array

4. Character set
ASCII: American standard information interchange code . Use a byte of 7 Bits can represent .
ISO8859-1: Latin code table . European Code watch Use a byte of 8 Who said .
GB2312: Chinese code table of China . Up to two bytes encode all characters .
GBK: China's Chinese coding table upgrade , It integrates more Chinese characters and symbols . Up to two text encodings
Unicode: International Standard Code , It's a fusion of all the characters currently used by humans . Assign a unique character code to each character . All the text is represented in two bytes .
UTF-8: Variable length encoding , You can use 1-4 Bytes to represent a character .5. Standard input 、 Output stream
(1) System.in: Standard input stream , Input from the keyboard by default System.out: Standard output stream , Output from the console by default
(2) adopt System Class setIn(InputStream is) / setOut(PrintStream ps) Method to specify the input and output streams
(3) practice : Enter a string from the keyboard , Request to read the whole line of string into uppercase output . Then proceed with the input operation , Until you type “e” perhaps “exit” when , Exit procedure .
Method 1 : Use Scanner Realization , call next() Returns a string
Method 2 : Use System.in Realization .System.in ---> Converted flow ---> BufferedReader Of readLine()
6. Print stream :PrintStream and PrintWriter
(1) Provides a series of overloaded print() and println()
(2) practice : Like the one below test1()

7. Data flow
(1)DataInputStream and DataOutputStream
(2) effect : A variable or string used to read or write basic data types

practice : Put the string in memory 、 The variables of the basic data type are written out to the file . Read the basic data type variables and strings stored in the file into memory , Save in variable .
Be careful :① When handling exceptions , You should still use try-catch-finally.
② Read different types of data in the same order as when the file was originally written , Keep the data in the same order !
8. Object flow
1.ObjectInputStream and ObjectOutputStream
2. effect : A processing stream used to store and read basic data type data or objects . His strength is that he can put java Write the object in to the data source , It can also restore objects from the data source .
3. Think of one java Objects are serializable , Need to meet the corresponding requirements . see Person.java
4. Serialization mechanism : The object serialization mechanism allows the java Object to platform independent binary stream , This allows this binary stream to be permanently stored on disk , Or transfer this binary stream over the network to another network node . When other programs get this binary stream , It can be restored to the original java object .
Serialization process : Put... In memory java Objects are saved to disk or transmitted over the network Use ObjectOutputStream Realization
Deserialization : Restore the object in the disk file to one in memory java object Use ObjectInputStream Realization
Custom classes implement serialization and deserialization operations
Person The following requirements need to be met , To serialize
1. Need to implement interface :Serializable
2. The current class provides a global constant :serialVersionUID
3. Except for the present Person Class needs to be implemented Serializable Beyond the interface , You must also ensure that all its internal properties must also be serializable .( By default , Basic data types are serializable )
Add :ObjectInputStream and ObjectOutputStream Cannot serialize static and transient Modified member variables
9. Random access file stream
RandomAccessFile Use
1.RandomAccessFile Directly inherited from java.lang.Object class , Realized DataInput and DataOutput Interface
2.RandomAccessFile It can be used as an input stream , It can also be used as an output stream
3. If RandomAccessFile As an output stream , If the written file does not exist , Is automatically created during execution ; If the file written to exists , The contents of the original file will be overwritten .( By default , Ab initio coverage )
4. You can use related operations , Realization RandomAccessFile“ Insert ” The effect of data


10. NIO.2 in Path、Paths、Files The use of the class

Path、Paths、Files The core API


Path Interface

Files class


边栏推荐
- STS download tutorial (the solution cannot be downloaded on the include official website)
- 象棋机器人「弄折了」棋童的手指。。。
- Guangdong: fire safety supervision is no longer "absent" in new industries and new formats such as script killing
- Iptables firewall
- Tlc549proteus simulation &sallen key filter &ad736vrms to DC conversion &proteus view 51 register value
- 【机器学习-白板推导系列】学习笔记---条件随机场
- npm踩坑
- Detailed explanation of hash table
- 关于离线缓存Application Cache /使用 manifest文件缓存
- Firewall firewall
猜你喜欢
Unexpected harvest of epic distributed resources, from basic to advanced are full of dry goods, big guys are strong!

Shell脚本文本三剑客之sed

Matlab draws Bode diagram with time delay system

Temporary use of solo, difficult choice of Blog

Analysis of the use of JUC framework from runnable to callable to futuretask

Guangdong: fire safety supervision is no longer "absent" in new industries and new formats such as script killing

Makefile template

严控室外作业时间!佛山住建局发文:加强高温期间建筑施工安全管理

Vscode removes style / syntax highlighting / code highlighting / black background when copying code

Principle of control system based on feedback rate
随机推荐
[machine learning whiteboard derivation series] learning notes - support vector machine and principal component analysis
JS string method summary
Idea: can't use subversion command line client: SVN solution
配置更改删除了路由过滤器,分布路由器不堪重负:加拿大网络大瘫痪
Tlc549proteus simulation &sallen key filter &ad736vrms to DC conversion &proteus view 51 register value
MySQL paging query instance_ MySQL paging query example explanation "suggestions collection"
广东:剧本杀等新行业新业态场所,消防安全监管不再“缺位”
【机器学习-白板推导系列】学习笔记---概率图模型和指数族分布
Kazoo tutorial
go入门篇 (4)
广东财政多举措助力稳住粮食安全“压舱石”
Sword finger offer notes: T53 - ii Missing numbers from 0 to n-1
omitempty在go中的使用
MySQL数据库主从复制集群原理概念以及搭建流程
go 用本地代码replace
Principle, concept and construction process of MySQL database master-slave replication cluster
npm踩坑
Example of MATLAB dichotomy (example of finding zero point by dichotomy)
Database cli tool docker image
LNMP architecture setup (deploy discuz Forum)