当前位置:网站首页>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
边栏推荐
- About web content security policy directive some test cases specified through meta elements
- 【从 0 开始学微服务】【03】初探微服务架构
- [statistical learning method] learning notes - support vector machine (I)
- 【统计学习方法】学习笔记——支持向量机(上)
- What if does not match your user account appears when submitting the code?
- Static comprehensive 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)
- 平安证券手机行开户安全吗?
- 数据库系统原理与应用教程(010)—— 概念模型与数据模型练习题
- Solutions to cross domain problems
猜你喜欢
Configure an encrypted web server
解决 Server returns invalid timezone. Go to ‘Advanced’ tab and set ‘serverTimezone’ property manually
SQL Lab (46~53) (continuous update later) order by injection
Solutions to cross domain problems
【PyTorch实战】图像描述——让神经网络看图讲故事
【统计学习方法】学习笔记——支持向量机(上)
Epp+dis learning path (1) -- Hello world!
EPP+DIS学习之路(1)——Hello world!
SQL head injection -- injection principle and essence
【PyTorch实战】用PyTorch实现基于神经网络的图像风格迁移
随机推荐
Epp+dis learning road (2) -- blink! twinkle!
[play RT thread] RT thread Studio - key control motor forward and reverse rotation, buzzer
2022广东省安全员A证第三批(主要负责人)考试练习题及模拟考试
Aike AI frontier promotion (7.7)
gcc 编译报错
About sqli lab less-15 using or instead of and parsing
Attack and defense world - PWN learning notes
Decrypt gd32 MCU product family, how to choose the development board?
Inverted index of ES underlying principle
【统计学习方法】学习笔记——第四章:朴素贝叶斯法
普乐蛙小型5d电影设备|5d电影动感电影体验馆|VR景区影院设备
2022-07-07日报:GAN发明者Ian Goodfellow正式加入DeepMind
Session
Several methods of checking JS to judge empty objects
What if does not match your user account appears when submitting the code?
SQL lab 21~25 summary (subsequent continuous update) (including secondary injection explanation)
In the small skin panel, use CMD to enter the MySQL command, including the MySQL error unknown variable 'secure_ file_ Priv 'solution (super detailed)
Learning and using vscode
ENSP MPLS layer 3 dedicated line
OSPF exercise Report