1.IO
1.1 Converting Stream
1.1.1 Overview
Input stream | output stream |
InputStreamReader | OutputStreamWriter |
Characteristic
(1) Conversion stream refers to the conversion of bytes to character stream, mainly InputStreamReader and OutputStreamWriter
(2)InputStreamReader mainly converts byte stream input stream to character input stream
(3)OutputStreamWriter mainly converts byte stream output stream to character output stream
1.1.2 InputStreamReader
public static void main(String[] args) { try (FileInputStream fis = new FileInputStream("C:/java/a.txt"); // Byte Input InputStreamReader isr = new InputStreamReader(fis); // Convert to character input BufferedReader br = new BufferedReader(isr);) { //Buffer Stream String temp=null; while((temp=br.readLine())!=null){ System.out.println(temp); } } catch (Exception e) { e.printStackTrace(); } }
1.2 Print Stream
1.2.1 Overview
Characteristic:
(1) Print stream is the most convenient class for output
(2) PrintStream containing bytes, PrintWriter containing characters
(3)PrintStream is a subclass of OutputStream. Passing an instance of an output stream to the print stream makes it easier to output content, which is equivalent to repackaging the output stream
(4) PrintStream class print() method is overloaded many times print(int i), print(boolean b), print(char c)
Standard Input/Output:
Java's standard input/output is represented by System.in and System.out, respectively. By default, it represents the keyboard and the display. When a program obtains input through System.in, it actually obtains input through the keyboard. When a program executes output through System.out, it always outputs to the screen.
Three methods of redirecting standard input/output are provided in the System class
- static void setErr(PrintStream err) redirects the Standard error output stream
- static void setIn(InputStream in) redirects "standard" input streams
- static void setOut(PrintStream out) redirects the Standard output stream
1.2.2 Use
public static void main(String[] args) { try(FileOutputStream fos=new FileOutputStream("C:/java/a.txt"); //Create Byte Input Stream PrintStream ps=new PrintStream(fos);) { //Encapsulate as Print Stream ps.println(); ps.println("How are you"); ps.println(true); ps.println(123456); System.out.println("Execution in progress..."); //Use System's own print stream to print to the console by default System.setOut(ps); //Change Print Location System.out.println("Test 1"); // Print to specified location, no longer to console System.out.println("Test 2"); System.out.println("Test 3"); System.out.println("Test 4"); System.out.println("Test 5"); } catch (Exception e) { e.printStackTrace(); } }
1.3 Object Flow, Serialization
1.3.1 Overview
Serialization: ObjectOutputStream saves objects to hard disk
Deserialization: ObjectInput loads objects from the hard disk into memory
Object creation: A clone of up to 2 reflection mechanisms 3 clone used by 1 new, obsolete, has been deserialized instead of 4 deserialized
Purpose: Long-term storage, object delivery
Scenario: Serialization is the conversion of a data object into a binary stream that allows data persistence and network transmission If the object is not serialized, then there is no way to store and transfer it
Deserialization is the reverse of serialization
Data Object-->Serialization-->Binary Stream-->Encryption Processing-->Network Transfer-->Decryption Processing-->Deserialization-->Data Object
For an object to be serialized, the class must implement the Serializable interface, which does not have any method functionality but is a tag
1.3.2 Serialization
public static void main(String[] args) throws Exception { User user = new User("Zhang San", 18); FileOutputStream fos = new FileOutputStream("C:/java/c"); // Create Output Stream ObjectOutputStream oos = new ObjectOutputStream(fos); // Create Object Flow oos.writeObject(user); // Write out objects oos.flush(); oos.close(); // Brush cache, turn off resources }
1.3.3 Deserialization
public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("C:/java/c"); ObjectInputStream ois=new ObjectInputStream(fis); Object o=ois.readObject(); System.out.println(o); User user=(User)o; user.m1(); }
1.3.4 Notes
To serialize an object, the class must implement the Serializable interface
import java.io.Serializable; public class User implements Serializable{ /** * If you do not change the class every time, the UID changes and needs to be re-serialized * * Purpose: To control the version of the serialized object. If the new version is compatible with the old version, the value does not need to be changed. If it is not compatible, the original serialized object cannot be used. * * version number */ private static final long serialVersionUID=1L; private String name; private transient int age; //transient: Variables decorated with it have property values that are not serialized, which can discard unnecessary data and improve the efficiency of serialization and deserialization public void m1() { System.out.println("==="); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }
1.4 serialVersionUID
If you do not change the class every time, the UID changes and needs to be re-serialized
Purpose: To control the version of the serialized object. If the new version is compatible with the old version, the value does not need to be changed. If it is not compatible, the original serialized object cannot be used.
version number
1.5 Transient
transient: Variables decorated with it have property values that are not serialized, which can discard unnecessary data and improve the efficiency of serialization and deserialization
1.6 File
1.6.1 Overview
java.io.File class: abstract representation of file and file directory paths, platform independent
lFile 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.
l To represent a real file or directory in a Java program, you must have a File object, but a File object in a Java program may not have a real file or directory.
The lFile object can be passed as a parameter to the constructor of the stream
1.6.2 Construction Method
1.6.3 Common Methods
Get functionality:
public String getAbsolutePath(): Get absolute path
public String getPath(): Get the path
public String getName(): Get the name
public String getParent(): Get the path to the upper file directory. If not, return null
public long length(): Gets the length of the file (that is, the number of bytes). Cannot get the length of the directory.
public long lastModified(): Get the last modification time, in milliseconds
public String[] list(): Gets an array of names of all files or file directories in the specified directory
public File[] listFiles(): Gets an array of Files for all files or file directories in the specified directory
Rename function:
public boolean renameTo(File dest): Rename the file to the specified file path
Judgement function:
public boolean isDirectory(): Determine if it is a file directory
public boolean isFile(): Determine if it is a file
public boolean exists(): Determine if there is one
public boolean canRead(): Determine if it is readable
public boolean canWrite(): Determine if it is writable
public boolean isHidden(): Determine whether to hide
Create delete function:
public boolean createNewFile(): Create a file. If the file exists, it is not created and false is returned
public boolean mkdir(): Create a 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 a file directory. If the upper file directory does not exist, create it together
Important: If you create a file or if the file directory does not have a drive letter path, it defaults to the project path.
public boolean delete(): Delete a file or folder
Remove precautions:
Deletes in Java do not go to the Recycle Bin.
To delete a file directory, note that it cannot contain files or file directories
1.6.4 Usage
public static void main(String[] args) throws IOException { // Create a file object File f1 = new File("C:\\Examination"); // Get full path System.out.println(f1.getAbsolutePath()); // Examination File Name/Folder Name System.out.println(f1.getName()); // Determine whether it is a file System.out.println(f1.isFile()); // Determine if it is a catalog System.out.println(f1.isDirectory()); // D:\18 Phase Parent Path System.out.println(f1.getParent()); // Parent directory object System.out.println(f1.getParentFile()); // Determine if the directory or file exists System.out.println(f1.exists()); f1 = new File("C:/a/b/c"); // System.out.println(f1.exists()); if (!f1.exists()) { // Recursively create the directory (no files are created) f1.mkdirs(); }else{ // Deleting c does not delete all ABCs System.out.println(f1.delete()+"---"); } f1 = new File("C:/a.txt"); if (!f1.exists()) { // Create a file, if it exists it will not be created, but will not create a directory // Returns true if created, false if not created boolean isCreate = f1.createNewFile(); System.out.println(isCreate); }else{ // There are // Delete the file f1.delete(); } f1 = new File("C:\\Courseware"); // Get all subfiles (direct subfiles) File[] subFile = f1.listFiles(); for (File file : subFile) { System.out.println(file.getName()); } }