IO flows through operations commonly used in import and export
1, File class
In the past, arrays and collections stored data in memory, but they were not persistent;
In all cases, we can use IO streams to store data on disk for persistence.
The way to create an object is directly through the constructor (new)
- public File(String pathname): creates a new pathname by converting the given pathname string to an abstract pathname
File instance. - public File(String parent, String child): creates a new path from the parent pathname string and the child pathname string
File instance. - public File(File parent, String child): creates a new path from the parent abstract pathname and child pathname strings
File instance.
Whether this file path exists or not, it has no practical significance if it does not exist, and no error will be reported.
Paths are case insensitive.
expand:
① In order to implement the cross platform use of path
Path delimiter (in java code, it must be \, / this is the escape character): file separator
Semicolon;: File.pathSeparator
eg: D:\test\test2.txt
String pathStr = "D:" + File.separator+"test"+ File.separator+"test2.txt";
② Absolute path: the path starting from the drive letter. This is a complete path.
Relative path: relative to the path of the project directory, this is a convenient path, which is often used in development
common method
public String getAbsolutePath(): returns the absolute pathname string of this File.
public String getPath(): converts this File to a pathname string.
public String getName(): returns the name of the File or directory represented by this File.
public long length(): returns the length of the File represented by this File. Cannot get the length of the directory.
public boolean exists(): whether the File or directory represented by this File actually exists.
public boolean isDirectory(): whether this File indicates a directory.
public boolean isFile(): this File indicates whether it is a File.
public boolean createNewFile(): creates a new empty file if and only if the file with this name does not exist yet
File.
public boolean delete(): deletes the File or directory represented by this File. (only empty folders can be deleted)
public boolean mkdir(): create the directory represented by this File. (a directory refers to a folder)
public boolean mkdirs(): create the directory represented by this File, including any required but nonexistent parent directory
public String[] list(): returns a String array representing all sub files or directories in the File directory.
public File[] listFiles(): returns a File array representing all sub files or directories in the File directory
expand
① Traversing the directory is to use the above methods;
② Recursion
Recursion must have conditions to end recursion; Efficiency is lower than cycle.
Recursive implementation logic:
Ⅰ. Direct recursion: method A calls method A
Ⅱ. Indirect recursion: method A calls method B, method B calls method C, and method C calls method A
2, IO stream
Classification of IO streams
flow | Input stream (abstract class) | usage | Output stream (abstract class) | usage |
---|---|---|---|---|
Byte stream | InputStram(File/path) | The read() of the implementation class FileInputStream is used | OutputStream(File/path) | The write() of the implementation class FileOutputStream is used |
Character stream | Reader(File/path | The read() of the implementation class FileReader is used | Writer(File/path) | The write() of the implementation class FileWriter is used |
Byte buffer stream | Bufferedinputstream (InputStream) (not an abstract class) | read() | BufferedOutputStream(OutputStream) (not an abstract class) | writer() |
Character buffer stream | BufferedReader (Reader) (not an abstract class) | readLine() | Bufferedwriter (writer) (not an abstract class) | writer() |
matters needing attention
- If there is no file in the path of IO stream creation, the file will be created directly. But the folder must have an error, otherwise the null pointer will report an error
- Output stream: write out code (memory) from memory to hard disk (code file)
- Input stream: read from hard disk to memory (file code) into code (memory)
- Byte stream: can operate any * * (Universal stream)**
- Character stream: only files of text document type can be manipulated
- Each operation of the output stream overwrites the previous data of the file. You can add true to indicate that you continue to write from the back
FileOutputStream outputStream = new FileOutputStream(file1, true); - The character stream must be closed before the data can be input and output
IO stream operation
Byte stream / character stream
- For byte stream, the number is stored in the file, which will be automatically converted into characters.
- The character stream must be closed before the data can be input and output.
- For the character stream, you can output and input multiple characters, using the character array cahr []
- For byte stream, you can output and input multiple bytes with byte array byte []
package com.example.demo002.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; public class test { private static final Logger logger = LoggerFactory.getLogger(test.class); public static void main(String[] args) { File file1 = new File("D:\\study\\test1.txt"); String pathStr = "D:" + File.separator+"study"+ File.separator+"test2.txt"; File file2 = new File(pathStr); System.out.println(file1.toString()); System.out.println(pathStr); FileOutputStream outputStream = null; FileInputStream inputStream = null; FileReader reader = null; FileWriter writer = null; byte[] bytesLen = new byte[3]; try { System.out.println("===========Byte stream=========="); // 1. Use of byte stream // 1.1 byte output stream (memory to symbol disk) and write to file outputStream = new FileOutputStream(file1, true); // 1.2 byte input stream (character disk to memory), reading files inputStream = new FileInputStream(file1); byte[] bytes = {97,98,99}; outputStream.write(65); outputStream.write(bytes); int read = inputStream.read(); // The first one is read by default, and the int type for is returned System.out.println("First read:" + (char)read); inputStream.read(bytesLen); // Read by length and store in byte array System.out.println("Second read:" + new String(bytesLen)); // 2. Character stream System.out.println("===========Character stream=========="); writer = new FileWriter(file2); reader = new FileReader(file2); writer.write(97); int read2 = reader.read(); System.out.println("First read" + (char)read2); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { outputStream.close(); inputStream.close(); writer.close(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
D:\study\test1.txt
D:\study\test2.txt
=Byte stream
15:39:06.668 [main] INFO com.example.demo002.service.test - start opening IO stream
First read: A
Second reading: abc
15:39:06.670 [main] INFO com.example.demo002.service.test - io stream started successfully
=Character stream
First read a
Buffer stream
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file)); BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
For character buffering
The output stream BufferedWriter has a newLine() method to represent line feed.
The input stream BufferedReader has a readLine() method to read a line of text. If it can't be read, null will be returned
Conversion flow
It is only useful for text documents (documents without pictures, so word can't)
InputStreamReader, byte stream to character stream
It is a subclass of Reader and a bridge from byte stream to character stream. It reads a word and decodes it into characters using the specified character set.
- Construction method
InputStreamReader(InputStream in): creates a character stream that uses the default character set.
InputStreamReader(InputStream in, String charsetName): creates a character with a specified character set
Flow.
public class ReaderDemo2 { public static void main(String[] args) throws IOException { // Define the file path. The file is gbk encoded String FileName = "E:\\file_gbk.txt"; // Create a stream object with the default UTF8 encoding InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName)); // Create a stream object and specify the GBK encoding InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK"); // Define variables and save characters int read; // Use the default encoding character stream to read, garbled while ((read = isr.read()) != -1) { System.out.print((char)read); // ��Һ� } isr.close(); // Read using the specified encoded character stream and parse normally while ((read = isr2.read()) != -1) { System.out.print((char)read);// hello everyone } isr2.close(); } }
OutputStreamWriter from character stream to byte stream
It is a subclass of Writer and a bridge from character stream to byte stream. Encodes characters into bytes using the specified character set. Its character set can be specified by name or accept the default character set of the platform.
- Construction method
OutputStreamWriter(OutputStream in): creates a character stream that uses the default character set.
OutputStreamWriter(OutputStream in, String charsetName): creates a character with a specified character set
Flow.
public class OutputDemo { public static void main(String[] args) throws IOException { // Define file path String FileName = "E:\\out.txt"; // Create a stream object with the default UTF8 encoding OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName)); // Write data osw.write("Hello"); // Save as 6 bytes osw.close(); // Define file path String FileName2 = "E:\\out2.txt"; // Create a stream object and specify the GBK encoding OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK"); // Write data osw2.write("Hello");// Save as 4 bytes osw2.close(); } }
Serialized stream
Java provides a mechanism for object serialization. An object can be represented by a byte sequence, which contains the number of objects
Data, object type, and properties stored in the object. After the byte sequence is written out to the file, it is equivalent to persisting the information of an object in the file. On the contrary, the byte sequence can also be read back from the file, reconstruct the object and deserialize it. Object data, object type and data information stored in the object can be used to create objects in memory. See the figure to understand serialization:
ObjectOutputStream class
Write out the original data type of Java object to the file to realize the persistent storage of the object
-
Construction method
public ObjectOutputStream(OutputStream out): creates a specified OutputStream
ObjectOutputStream. -
Serialization operation
- To serialize an object, two conditions must be met:
This class must implement Java io. Serializable interface. Serializable is a tag interface and does not implement this interface
Class will not serialize or deserialize any state and will throw NotSerializableException.
All properties of this class must be serializable. If a property does not need to be serializable, the property must be noted as transient
, use the transient keyword to modify.
public class Employee implements java.io.Serializable { public String name; public String address; public transient int age; // Transient is a transient decorated member and will not be serialized public void addressCheck() { System.out.println("Address check : " + name + " -- " + address); } }
2. Write out object methods
- public final void writeObject (Object obj): writes out the specified object.
public class SerializeDemo{ public static void main(String [] args) { Employee e = new Employee(); e.name = "zhangsan"; e.address = "beiqinglu"; e.age = 20; try { // Create serialized stream object ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt")); // Write out object out.writeObject(e); // Release resources out.close(); fileOut.close(); System.out.println("Serialized data is saved"); // The name and address are serialized, Age is not serialized. } catch(IOException i) { i.printStackTrace(); } } } Output results: Serialized data is saved
ObjectInputStream class
ObjectInputStream deserializes the stream and restores the original data previously serialized with ObjectOutputStream to objects.
- Construction method
public ObjectInputStream(InputStream in): creates a specified InputStream
ObjectInputStream. - Deserialization operation 1
If we can find the class file of an object, we can deserialize it and call ObjectInputStream to read the class file of the object
method:
public final Object readObject(): reads an object.
public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { // Create deserialized stream FileInputStream fileIn = new FileInputStream("employee.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); // Read an object e = (Employee) in.readObject(); // Release resources in.close(); fileIn.close(); }catch(IOException i) { // Catch other exceptions i.printStackTrace(); return; }catch(ClassNotFoundException c) { // The capture class cannot find an exception System.out.println("Employee class not found"); c.printStackTrace(); return; } // No abnormality, direct printout System.out.println("Name: " + e.name); // zhangsan System.out.println("Address: " + e.address); // beiqinglu System.out.println("age: " + e.age); // 0 } }
For a JVM to deserialize an object, it must be a class that can find a class file. If the class file of the class cannot be found, an
A ClassNotFoundException exception.
- Deserialization operation 2
In addition, when the JVM deserializes the object, the class file can be found, but the class file is modified after serializing the object, then
The deserialization operation will also fail, throwing an InvalidClassException. The reasons for this exception are as follows:
- The serial version number of the class does not match the version number of the class descriptor read from the stream
- The class contains an unknown data type
- This class has no accessible parameterless constructor
The Serializable interface provides a serial version number to the class to be serialized. serialVersionUID the target of the version number
The is to verify whether the serialized object and the corresponding class match.
public class Employee implements java.io.Serializable { // Add serial version number private static final long serialVersionUID = 1L; public String name; public String address; // Add a new attribute, recompile, deserialize, and assign this attribute as the default value public int eid; public void addressCheck() { System.out.println("Address check : " + name + " -- " + address); } }