当前位置:网站首页>Day-20 file operation, recursive copy, serialization
Day-20 file operation, recursive copy, serialization
2022-07-07 12:36:00 【Xiaobai shelter】
1.File
1.1 summary
java.io.File class : Abstract representation of files and file directory paths , It's not about the platform
File It can be built 、 Delete 、 Rename files and directories , but File Can't access the file content itself
If you need to access the file content itself , You need to use input / Output stream
Want to be in java A program that represents a real-life file or directory , Then there must be a File object , however java One of the procedures File object , There may not be a real file or directory
File Object can be passed as a parameter to the constructor of the stream
1.2 Construction method
public File(String pathname) With pathname Create... For the path File object , It can be absolute path or relative path , If pathname Is a relative path , The default current path is in the system property user.dir Storage in .
Absolute path : It's a fixed path , Start with the drive
Relative paths : It's about starting from a certain position
public File(String parent,String child) With parent The path of fatherhood ,child Create... For the subpath File object .
public File(File parent,String child) According to a father File Object and sub file path penetrations File object
1.3 Usage mode
//windows of use \ Express , But in java in \ Is an escape character , So write two
//linux of use / Express
// But now the system has been optimized better , It doesn't matter to mix it up
//File.separator: It mainly solves the problem of separator ,window The system is \\linux The system is /
File file=new File("D:"+File.separator+"TianLg");
// Get full path D:\TianLg
System.out.println(file.getAbsolutePath());
// file / Folder name courseware
System.out.println(file.getName());
// Superior directory D:\
System.out.println(file.getParent());
// The file object corresponding to the parent directory
System.out.println(file.getParentFile());
// Determine if it's a directory true
System.out.println(file.isDirectory());
// Judge whether it exists true
System.out.println(file.exists());
file=new File("D:/a.txt");
// create a file , No directory will be created , If it already exists , Don't create
// If you create return ture, Otherwise return to false
System.out.println(file.createNewFile());
// Delete file , Delete successful return true, Otherwise return to false
System.out.println(file.delete() );
file=new File("D:/TianLg");
// Get all sub file objects
File[] subFiles= file.listFiles();
for(File file1: subFiles){
System.out.println(file1.getName());
}
file=new File("D:/com/zrz");
// Create directory , If the superior directory does not exist , Do not create
// establish zrz, But if not com, Do not create
//file.mkdir();
// Create directory , If the superior directory does not exist , Just create the parent directory
file.mkdirs();
// When deleting a directory , Will only delete zrz It doesn't delete com, because file yes zrz File object
file.delete();
}
1.4 Recursive replication
1. Copy : Is the combination of input and output
2. Get all sub files under the folder
If the sub file is a file , Copy
If the sub file is a directory , Then get all the sub files of the directory again , Do the same thing
Be careful : When copying , The source directory and destination directory cannot be consistent Otherwise, the file will be lost
public class IO_FileCopy_03 {
public static void main(String args[]){
String filePath="D:/TianLg";
copyMenu(new File(filePath));
System.out.println(" Copy complete ");
}
public static void copyMenu(File file){
//1. Determine if it's a document
if(file.isFile()){
// It's a document , Copy
//2. Get the full path of the file , And create the corresponding input stream
String filePath=file.getAbsolutePath();
//3. Get the full path of the written file , And create the corresponding output stream
// Write out the directory and die , It's just D Copy data from disk to E In the middle of the plate
String newFilePath="E"+filePath.substring(1);
// Determine whether the target directory exists , Create... If it doesn't exist
File supFile=new File(newFilePath).getParentFile();
if(!supFile.exists()){
supFile.mkdirs();
}
//4 Copy
try(FileInputStream fis=new FileInputStream(filePath);
FileOutputStream fos=new FileOutputStream(newFilePath);
BufferedInputStream bis=new BufferedInputStream(fis);
BufferedOutputStream bos=new BufferedOutputStream(fos);
){
byte[] bytes=new byte[fis.available()+10];
int temp=0;
while((temp=bis.read(bytes))!=-1){
bos.write(bytes, 0, temp);
}
bos.flush();
System.out.println(file.getName()+" Replication success ");
}
catch(Exception e){
e.printStackTrace();
}
}
else{
// Is a directory , Get all the files in the directory , Making judgments ( Recursively pass the sub file object into the current method again for operation )
// Call all sub files of this directory
File[] subFiles=file.listFiles();
// Importing all sub files copyMenu In the method , In determining whether it is a file or a folder
for(File file2:subFiles){
copyMenu(file2);
}
}
}
}
2. Object flow
2.1 summary
How to create objects
1.new Most used
2. The reflex mechanism You can create the corresponding object through a string
3.clone Object The method in , Has been abandoned , Replaced by serialization
4. serialize
serialize :
Put the heap memory of java object , Persistence is stored in the local hard disk
Deserialization
Serialize the objects in the hard disk , Deserialize to heap memory object
advantage :
It can be preserved for a long time
More conducive to data transmission
Application scenarios
Serialization is to convert data into a binary stream for long-term storage , If not serialized , Long term storage and network delivery are not allowed
Network transmission process
Data objects –> serialize –> Binary stream –> Encryption processing –> Network transmission –> Decryption processing –> Binary stream –> Deserialization –> Data objects
Be careful : Want to be serialized , Must be realized Serializable Interface , This interface is an identifier
2.3 serialize
public class IO_04_ObjectOutputStream {
public static void main(String args[]){
User user=new User("admin","root", 0);
//System.out.println(user);
try(FileOutputStream fos=new FileOutputStream("./src/user");
ObjectOutputStream oos=new ObjectOutputStream(fos);
){
// Write
oos.writeObject(user);
oos.flush();
}
catch(Exception e){
e.printStackTrace();
}
}
}
2.4 Deserialization
public class IO_05_ObjectInputStream {
public static void main(String args){
try(FileInputStream fis=new FileInputStream("./src/user");
ObjectInputStream ois=new ObjectInputStream(fis);
){
// Reading data
Object object=ois.readObject();
User user=(User) object;
System.out.println(user.getPassword());
// Move down
System.out.println(user.getPassword());
user.m1();
user.m2();
}catch(Exception e){
e.printStackTrace();
}
}
}
2.5 serialVersionUID
After each class change , Will declare a new version , At this time, if the serialized object does not correspond to the version in the class , You're going to report a mistake
InvalidClassException
If Now we just add a new attribute , Want downward compatibility , At this time, we need to manually control the version number
Otherwise, after each class change , Need to re serialize and deserialize
Values can be defined at will , Because it only defines a version bridge between classes and objects
2.6Transient
transient Modifier , Decorated properties cannot be serialized
You can put unnecessary data , use transient modification , This can improve the efficiency of serialization and deserialization
边栏推荐
- Connect to blog method, overload, recursion
- 【深度学习】图像多标签分类任务,百度PaddleClas
- Tutorial on principles and applications of database system (010) -- exercises of conceptual model and data model
- SQL Lab (32~35) contains the principle understanding and precautions of wide byte injection (continuously updated later)
- AirServer自动接收多画面投屏或者跨设备投屏
- 数据库安全的重要性
- Common knowledge of one-dimensional array and two-dimensional array
- The IDM server response shows that you do not have permission to download the solution tutorial
- The left-hand side of an assignment expression may not be an optional property access. ts(2779)
- Aike AI frontier promotion (7.7)
猜你喜欢

Common knowledge of one-dimensional array and two-dimensional array

BGP third experiment report

【深度学习】图像多标签分类任务,百度PaddleClas

数据库系统原理与应用教程(007)—— 数据库相关概念

Pule frog small 5D movie equipment | 5D movie dynamic movie experience hall | VR scenic area cinema equipment

Epp+dis learning road (2) -- blink! twinkle!

【PyTorch实战】用RNN写诗

VSCode的学习使用
![[statistical learning methods] learning notes - Chapter 5: Decision Tree](/img/0e/c60e04ab4a7ae4728cc76eff1c028a.png)
[statistical learning methods] learning notes - Chapter 5: Decision Tree

leetcode刷题:二叉树19(合并二叉树)
随机推荐
Hi3516 full system type burning tutorial
MPLS experiment
【统计学习方法】学习笔记——逻辑斯谛回归和最大熵模型
In the small skin panel, use CMD to enter the MySQL command, including the MySQL error unknown variable 'secure_ file_ Priv 'solution (super detailed)
金融数据获取(三)当爬虫遇上要鼠标滚轮滚动才会刷新数据的网页(保姆级教程)
Aike AI frontier promotion (7.7)
idea 2021中文乱码
数据库系统原理与应用教程(008)—— 数据库相关概念练习题
对话PPIO联合创始人王闻宇:整合边缘算力资源,开拓更多音视频服务场景
Tutorial on the principle and application of database system (008) -- exercises on database related concepts
[play RT thread] RT thread Studio - key control motor forward and reverse rotation, buzzer
Preorder, inorder and postorder traversal of binary tree
Object. Simple implementation of assign()
爱可可AI前沿推介(7.7)
The IDM server response shows that you do not have permission to download the solution tutorial
数据库系统原理与应用教程(011)—— 关系数据库
Epp+dis learning path (1) -- Hello world!
图像像素读写操作
解决 Server returns invalid timezone. Go to ‘Advanced’ tab and set ‘serverTimezone’ property manually
TypeScript 接口继承