IO
File
file: Abstract paths and files 1. Objects are created without paying attention to the current path or the existence of files. 2. Platform-independent path separators File.pathSeparator path Terminator File.separator path splitter Common methods: File f = new File(); f.canExecute() to see if executable f.canRead() is readable f.createNewFile() Create a file successfully f.getAbsolutePath() Gets the absolute path; f.getPath () Gets the relative path f.getName() Gets the filename f.getTotalSpace() Gets the total size getusableSpace() Gets the available size The difference between mkdir and mkdirs: The former can only create a first-level directory, while the latter can create a multi-level directory.
io
Why do I need io? 1. The file class itself can only operate on the metadata of the file or directory (except the content itself), and can not do anything about the content of the file. 2. Up to now, our means of storage are very limited and problematic. Learned storage means: Variables, objects, arrays, and storage are in memory. Data exists after the program starts; data is lost when the program is destroyed But during the whole coding and project process, we must store the data permanently, which is convenient for later use and update. 3. Data cannot be persisted Solution: Through the knowledge of IO flow, the data can be written to the file or read the data information in the file. Files are stored on disk. After the computer shuts down, the data is still there.
io(input/output):
Classification of IO Flows
1. According to the type of data output: Byte streams: Byte input and output streams Character Stream: Character Input and Output Streams 2. According to the direction of flow: Input stream and output stream 3. According to the processing function: Node flow Processing flow
Node Flow and Processing Flow
/// Writer out = new Output Stream Writer (os); for processing flow // OutputStream os = new FileOutputStream("a.txt"); and // BufferedWriter bw = new BufferedWriter(out); for node flow public class Test05 { public static void main(String[] args) throws IOException { //create object OutputStream os = new FileOutputStream("a.txt"); Writer out = new OutputStreamWriter(os); BufferedWriter bw = new BufferedWriter(out); //write bw.write("I laughed at the sky with my knife"); bw.newLine(); bw.write("Two Kunlun Mountains of Liver and Gallbladder"); bw.flush(); bw.close(); out.close(); os.close(); } }
InputStream
FileInputStream
Read data: Byte streams: InputStream is the parent of all byte streams Input: Subclass: FileInputStream file byte input stream, data source in the file, read by word section, flow direction input
Loop read: Each time data is read, only one byte can be read. When read through the read method, if read to the end of the file, return - 1. FileInputStream ensures that the file exists during cyclic reading
public static void main(String[] args) throws IOException { //1: Create objects InputStream is = new FileInputStream("C:\\Users\\wawjy\\Desktop\\cc.txt"); int num = 0; //2: Read data while((num=is.read())!=-1) { //3: Analytical data System.out.println("Read data:"+num); } //4: Closing resources is.close(); }
Read multiple bytes
Read an array of bytes at once public static void main(String[] args) throws IOException { //Declare objects InputStream is = new FileInputStream("C:\\Users\\wawjy\\Desktop\\cc.txt"); //Read data //Declare a byte array byte[] buf = new byte[1024]; //Reading the length of a byte array returns the length of the byte array read int len = is.read(buf); //Read the data into buf //Analytical data String msg = new String(buf,0,len); System.out.println(msg); //close resource is.close(); }
Handling exceptions
package com.mage.Io; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class Test { public static void main(String[] args) { InputStream is=null; try { is = new FileInputStream("C:\\aa.txt"); byte[] buf = new byte[1024]; int len = is.read(buf); String msg = new String(buf,0,len); System.out.println(msg); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
ObjectInputStream
package com.mage.Io; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; public class Test01 { public static void main(String[] args) throws FileNotFoundException, IOException { //create object ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt")); //Read data int num = ois.readInt(); //output data System.out.println(num); //Read data double d = ois.readDouble(); //output data System.out.println(d); //Read data String s = ois.readUTF(); //output data System.out.println(s); //Close ois.close(); } }
OutputStream
FileOutputStream
Byte output stream: The parent class of all byte output streams The subclass is FileOutputStream, the destination of output is file, and the type of output is byte. When output, if the file does not exist, the file will be created, but no non-existent directory will be created.
Write multiple characters
When creating a FileOutputStream object, the second parameter is boolean, which indicates whether to append content after the file. By default, false does not append.
public static void main(String[] args) throws IOException { //create object OutputStream os = new FileOutputStream("aaa.a",true); //Declarations Written Data String msg = "laoxuezhideniyongyou"; //write os.write(msg.getBytes(),0,10); //10 Represents Length //close resource os.close(); }
serialization and deserialization
(Object Input Stream, Object Output Stream) The process that the output stream of the object writes the specified object to the file is the process of serializing the object. The process that the input stream of the object reads the specified serialized file is the process of deserializing the object.
Serialization of objects
package com.mage.Io.outputstream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Test { public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException { write(); read(); } public static void write() throws FileNotFoundException, IOException { //create object User u =new User("linzhengaugn",1,22); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("aa.txt")); //Write data oos.writeObject(u); //Refresh and close resources oos.flush(); oos.close(); } public static void read() throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("aa.txt")); Object obj = ois.readObject(); System.out.println(obj); ois.close(); } } class User implements Serializable{ private String name; private int gender; private int age; public User() { } public User(String name,int gender,int age) { super(); this.name = name; this.gender=gender; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", gender=" + gender + ", age=" + age + "]"; } }
Results (output of console and file aa.txt)
If transient is added to the above code (the value corresponding to the current property is not serialized when serialized, and the value is changed to the default value)
class User implements Serializable{ private transient String name; private int gender; private transient int age; public User() { }
Result
[External Link Picture Transfer Failure (img-wFvbj67n-1564294124716)] https://i.loli.net/2019/07/27/5d3be95251d5714824.png)]
Serialized id
When serializing, remember to add the serialized version number to ensure that after the output is modified, the reader will not report errors. class User implements Serializable{ // serialized id private static final long serialversionUID = 1L; private String name; private int gender; private int age;
The impact on singletons
The readResolve method in the class is invoked by default when the program is serialized. If this method is not overridden, a copy of the object of the current class is returned each time. This copy is a new object, leading to the destruction of the singleton pattern.
package com.mage.Io; import java.io.Serializable; public class Lazy implements Serializable{ private static Lazy lazy = null; private Lazy() { } public static Lazy getInstance() { if(lazy==null) { new Lazy(); } return lazy; } public Object readResolve() { return lazy; } }
Copy and paste
public static void CtrlCV(String srcFile,String destFile) throws IOException{ /* //1:Declare copy and paste file objects String srcFile = "C:\\Users\\wawjy\\Desktop\\1.jpg"; String destFile = "123.jpg"; */ //2: Declare objects InputStream is = new FileInputStream(srcFile); OutputStream os = new FileOutputStream(destFile); //3: Read files int len = 0; while((len=is.read())!=-1) { //Write out os.write(len); } os.close(); is.close(); }
Reader
InputStreamReader
public class Test03 { public static void main(String[] args) throws FileNotFoundException,IOException{ //create object InputStream is = new FileInputStream("a.txt"); Reader r = new InputStreamReader(is); //Specified Character Set //Reader reader = new InputStreamReader(new FileInputStream("c.txt"),"utf-8"); //read char[] chs = new char[1024]; int count = r.read(chs); //Analysis results System.out.print(new String(chs,0,count)); //close resource r.close(); is.close(); } }
Buffered Reader
StringBuilder is used to create objects in the same way as Reader
public class Test02 { public static void main(String[] args) throws IOException { //Create objects in the same way as Reader BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream("a.txt"))); //read String str = null; StringBuilder sb = new StringBuilder(); while((str=reader.readLine())!=null) { sb.append(str); sb.append("\r\n"); } System.out.println(sb.toString()); //close resource reader.close(); } }
Writer
public class Test02 { public static void main(String[] args) throws IOException { //create object Writer out = new OutputStreamWriter(new FileOutputStream("a.txt")); //Declare output data String str = "you a good a"; //output //out.write(str.toCharArray()); out.write(str); //Refresh out.flush(); //Close out.close(); } }
BufferedWriter
public class Test05 { public static void main(String[] args) throws IOException { //create object OutputStream os = new FileOutputStream("a.txt"); Writer out = new OutputStreamWriter(os); BufferedWriter bw = new BufferedWriter(out); //write bw.write("I laughed at the sky with my knife"); bw.newLine(); bw.write("Two Kunlun Mountains of Liver and Gallbladder"); bw.flush(); bw.close(); out.close(); os.close(); } }