当前位置:网站首页>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
边栏推荐
- The road to success in R & D efficiency of 1000 person Internet companies
- 跨域问题解决方案
- Attack and defense world - PWN learning notes
- Static routing assignment of network reachable and telent connections
- DOM parsing XML error: content is not allowed in Prolog
- Using stack to convert binary to decimal
- 【统计学习方法】学习笔记——第五章:决策树
- Cookie
- leetcode刷题:二叉树23(二叉搜索树中的众数)
- 数据库系统原理与应用教程(010)—— 概念模型与数据模型练习题
猜你喜欢
JS to convert array to tree data
BGP actual network configuration
【统计学习方法】学习笔记——第五章:决策树
"Series after reading" my God! It's so simple to understand throttling and anti shake~
The road to success in R & D efficiency of 1000 person Internet companies
消息队列消息丢失和消息重复发送的处理策略
【统计学习方法】学习笔记——逻辑斯谛回归和最大熵模型
H3C HCl MPLS layer 2 dedicated line experiment
Hi3516 full system type burning tutorial
BGP third experiment report
随机推荐
爱可可AI前沿推介(7.7)
Decrypt gd32 MCU product family, how to choose the development board?
Minimalist movie website
广州市召开安全生产工作会议
An error occurred when vscade tried to create a file in the target directory: access denied [resolved]
SQL injection -- Audit of PHP source code (take SQL lab 1~15 as an example) (super detailed)
图形对象的创建与赋值
解密GD32 MCU产品家族,开发板该怎么选?
[statistical learning method] learning notes - logistic regression and maximum entropy model
Cenos openssh upgrade to version 8.4
SQL blind injection (WEB penetration)
Several ways to clear floating
idea 2021中文乱码
sql-lab (54-65)
Will the filing free server affect the ranking and weight of the website?
[play RT thread] RT thread Studio - key control motor forward and reverse rotation, buzzer
Sort out the garbage collection of JVM, and don't involve high-quality things such as performance tuning for the time being
编译 libssl 报错
H3C HCl MPLS layer 2 dedicated line experiment
跨域问题解决方案