Day16 learning java (File operation, recursive copy, serialization)

File

summary

java.io.File class: the abstract representation of file and file directory path, which is platform independent

File can create, delete and rename files and directories, but file cannot access the file content itself. If you need to access the file content itself, you need to use input / output streams.

To represent a real File or directory in a Java program, there must be a File object, but a File object in a Java program may not have a real File or directory.

The File object can be passed as a parameter to the constructor of the stream

Construction method

public File(String pathname) creates a File object with pathname as the path, which can be an absolute path or a relative path. If pathname is a relative path, the default current path is in the system attribute user Stored in dir.
Absolute path: it is a fixed path, starting from the drive letter
Relative path: starts relative to a position
public File(String parent,String child) creates a File object with parent as the parent path and child as the child path.
public File(File parent,String child) creates a File object based on a parent File object and a child File path

common method

Get function:
 public String getAbsolutePath(): get the absolute path
 public String getPath(): get the path
 public String getName(): get the name
 public String getParent(): get the directory path of the upper level file. If none, null is returned
 public long length(): obtain the file length (i.e. number of bytes). Cannot get the length of the directory.
 public long lastModified(): obtain the last modification time, in milliseconds
 public String[] list(): get the name array of all files or file directories under the specified directory
 public File[] listFiles(): get the File array of all files or File directories in the specified directory
Rename function:
 public boolean renameTo(File dest): rename the file to the specified file path
Judgment function:
 public boolean isDirectory(): judge whether it is a file directory
 public boolean isFile(): judge whether it is a file
 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(): judge whether to hide
Create delete function:
 public boolean createNewFile(): create a file. If the file exists, it will not be created and false will be returned
 public boolean mkdir(): create file directory. If this file directory exists, it will not be created. If the upper directory of this file directory does not exist, it will not be created.
 public boolean mkdirs(): create file directory. If the upper file directory does not exist, create it together
Note: if you create a file or the file directory does not have a write letter path, it is under the project path by default.
 public boolean delete(): delete files or folders
Precautions for deletion:
Delete in Java does not go to the recycle bin.
To delete a file directory, please note that the file directory cannot contain files or file directories

Mode of use

public class IO_01_File {

	public static void main(String[] args) throws IOException {
		// In windows, it is represented by \, but in java \, it is a translator, so we need to write two
		// / is used in linux
		// But now the system optimization is very good, and it doesn't matter to mix it
		// File.separator: it mainly solves the separator problem. The window system is \ linux/
		File file = new File("D:" + File.separator + "cym" + File.separator
				+ "a.txt");
		// Get full path
		System.out.println(file.getAbsolutePath());
		// File / folder name
		System.out.println(file.getName());
		// Parent directory
		System.out.println(file.getParent());
		// File object corresponding to parent directory
		System.out.println(file.getParentFile());
		// Determine whether it is a file
		System.out.println(file.isFile());
		// Determine whether it is a directory
		System.out.println(file.isDirectory());
		// Judge whether it exists
		System.out.println(file.exists());
		file = new File("D:/cym/a.txt");
		// If you create a file, you will not create a directory. If it already exists, you will not create it
		// If it is created, it returns true; otherwise, it returns false
		System.out.println(file.createNewFile());
		// If the file is deleted, true will be returned if the deletion is successful; otherwise, false will be returned
		System.out.println(file.delete());
		file = new File("D:/cym");
		// Get all sub file objects
		File[] subFiles = file.listFiles();
		for (File file1 : subFiles) {
			System.out.println(file1.getName());
		}
		file = new File("D:/cym/cym1");
		// Create a directory. If the parent directory does not exist, it will not be created
		// Create cym1, but not if there is no CYM
		file.mkdir();
		// Create a directory. If the parent directory does not exist, create the parent directory
		// file.mkdirs();
		// When deleting a directory, only cym1 will be deleted, not CYM, because file is a cym1 file object
		file.delete();
	}

}

When copying, the source directory and target directory cannot be consistent

public class IO_02_FileCopy {

	public static void main(String[] args) {
		// When creating an output stream, if it is overwritten writing, the contents of the corresponding file will be cleared when creating an object, resulting in failure to read the data when reading
		// If it is set to append write, it will never finish reading
		// But using buffered streams can solve this problem
		try (FileInputStream fis = new FileInputStream("D:/cym/a.txt");
				BufferedInputStream bis = new BufferedInputStream(fis);
				FileOutputStream fos = new FileOutputStream("D:/cym/a.txt",
						true);
				BufferedOutputStream bos = new BufferedOutputStream(fos);) {
			int temp = 0;
			byte[] bytes = new byte[10];
			while ((temp = bis.read(bytes)) != -1) {
				bos.write(bytes, 0, temp);
			}
			bos.flush();
			System.out.println("complete");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Recursive replication

public class IO_03_FileCopy {

	public static void main(String[] args) {
copyMenu(new File("D:/abcd"));
	}

	public static void copyMenu(File file) {
		// 1. Judge whether it is a document
		if (file.isFile()) {
			// Yes, copy
			// 2. Get the full path of the file
			String filePath = file.getAbsolutePath();
			// 3. Get the full path of the written file and create the corresponding output stream
			// Write out the directory and copy the data in disk D to disk E
			String newFilePath = "E" + filePath.substring(1);
			// Judge whether the target directory exists. If it does not exist, create it
			File supFile = new File(newFilePath).getParentFile();
			if (!supFile.exists()) {
				supFile.mkdirs();
			}
			// 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() + "Copy successful");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// If it is a directory, get all the files under the directory, and then judge, that is, recursively pass the sub file object into the current method again
			File[] subFiles = file.listFiles();
			for (File f : subFiles) {
				copyMenu(f);
			}
		}
	}

}

Object flow

summary

How objects are created

  •  1.new: Most used
    
  •  2.Reflection mechanism: the corresponding object can be created through a string
    
  •  3.clone Object The method in has been discarded and replaced by serialization
    
  •  4.serialize
    

Serialization: persist the java objects in the heap memory in the local hard disk

Deserialization: deserialize the serialized files in the hard disk into heap memory objects

advantage:

  • It can be stored for a long time
    
  •  	More conducive to data transmission
    

Application scenario

  •  	Serialization is to convert data into binary stream for long-term storage. Without serialization, long-term storage and network transmission cannot be carried out
    

Network transmission process:

  •  	data object→serialize→Binary stream→Encryption processing→network transmission→Decryption processing→Binary stream→Deserialization→data object
    

be careful

To be serialized, you must implement the Serializable interface. The interface has no method, which is just an identification to indicate that the class can be serialized

The following statement is required

serialize

public class IO_04_ObjectOutputStream {

	public static void main(String[] args) {
		Student s = new Student(18, "Zhang San");
		System.out.println(s);
		try (FileOutputStream fos = new FileOutputStream("./src/_1_22/s");
				ObjectOutputStream oos = new ObjectOutputStream(fos);) {
			// Write
			oos.writeObject(s);
			oos.flush();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

Deserialization

public class IO_05_ObjectInputStream {

	public static void main(String[] args) {
		try (FileInputStream fis = new FileInputStream("./src/_1_22/s");
				ObjectInputStream ois = new ObjectInputStream(fis);) {
			// Read data
			Object o = ois.readObject();
			System.out.println(o);
			//Downward transformation
			Student s = (Student)o;
			System.out.println(s.age);
			s.m1();
			s.m2();
		}

		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

serialVersionUID

Each time the class is updated, a new version will be declared. At this time, if the serialized object does not correspond to the previous version in the class, an error will be reported
If only one attribute is added and we want downward compatibility, we need to manually control the version number, otherwise we have to re serialize and deserialize after each update
Values can be defined arbitrarily because they are just a version bridge between a class and an object

Transient

Transient modifier. Modified attributes cannot be serialized. Unnecessary tutorials can be modified with transient, which can improve the efficiency of serialization and deserialization

Keywords: Java Back-end

Added by SBro on Thu, 27 Jan 2022 02:08:35 +0200