1.IO flow cases
1.1 improved version of collection to file data sorting [application]
1.1. 1 case requirements
- Enter 5 student information (name, Chinese score, mathematics score and English score) on the keyboard. It is required to write the text file from high to low according to the total score
- Format: name, Chinese score, math score, English score example: Lin Qingxia, 98,99100
1.1. 2 analysis steps
- Define student classes
- Create a TreeSet collection and sort by comparator sorting
- Enter student data with keyboard
- Create a student object and assign the data entered on the keyboard to the member variable of the student object
- Add the student object to the TreeSet collection
- Create character buffered output stream object
- Traverse the collection to get each student object
- Splice the data of the student object into a string in the specified format
- Call the method of character buffered output stream object to write data
- Release resources
1.1. 3 code implementation
- Student class
public class Student { // full name private String name; // grade scores of Chinese private int chinese; // Mathematics achievement private int math; // English achievement private int english; public Student() { super(); } public Student(String name, int chinese, int math, int english) { super(); this.name = name; this.chinese = chinese; this.math = math; this.english = english; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getChinese() { return chinese; } public void setChinese(int chinese) { this.chinese = chinese; } public int getMath() { return math; } public void setMath(int math) { this.math = math; } public int getEnglish() { return english; } public void setEnglish(int english) { this.english = english; } public int getSum() { return this.chinese + this.math + this.english; } }
- Test class
public class TreeSetToFileDemo { public static void main(String[] args) throws IOException { //Create a TreeSet collection and sort by comparator sorting TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { //Total score from high to low int num = s2.getSum() - s1.getSum(); //minor criteria int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num; int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2; int num4 = num3 == 0 ? s1.getName().compareTo(s2.getName()) : num3; return num4; } }); //Enter student data with keyboard for (int i = 0; i < 5; i++) { Scanner sc = new Scanner(System.in); System.out.println("Please enter page" + (i + 1) + "Student information:"); System.out.println("full name:"); String name = sc.nextLine(); System.out.println("Language achievement:"); int chinese = sc.nextInt(); System.out.println("Math scores:"); int math = sc.nextInt(); System.out.println("English score:"); int english = sc.nextInt(); //Create a student object and assign the data entered on the keyboard to the member variable of the student object Student s = new Student(); s.setName(name); s.setChinese(chinese); s.setMath(math); s.setEnglish(english); //Add the student object to the TreeSet collection ts.add(s); } //Create character buffered output stream object BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\ts.txt")); //Traverse the collection to get each student object for (Student s : ts) { //Splice the data of the student object into a string in the specified format //Format: name, Chinese score, math score, English score StringBuilder sb = new StringBuilder(); sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getEnglish()).append(",").append(s.getSum()); //Call the method of character buffered output stream object to write data bw.write(sb.toString()); bw.newLine(); bw.flush(); } //Release resources bw.close(); } }
1.2 copy single level folder [ application ]
1.2. 1 case requirements
- Copy the folder "E:\itcast" to the module directory
1.2. 2 analysis steps
- Create a data source directory File object with the path E:\itcast
- Gets the name of the File object in the data source directory
- Create a destination directory File object. The path consists of (module name + name obtained in step 2)
- Judge whether the File created in step 3 exists. If it does not exist, create it
- Get the File array of all files in the data source directory
- Traverse the File array to get each File object, which is actually the data source File
- Gets the name of the File object of the data source File
- Create a destination File object. The path consists of (destination directory + the name obtained in step 7)
- Copy file
Because it is not clear what type of files are in the data source directory, byte stream is used to copy files
The construction method with the parameter File is adopted
1.2. 3 code implementation
public class CopyFolderDemo { public static void main(String[] args) throws IOException { //Create a data source directory File object with the path E:\itcast File srcFolder = new File("E:\\itcast"); //Get the name of the File object in the data source directory (itcast) String srcFolderName = srcFolder.getName(); //Create a destination directory File object. The path name is composed of module name + itcast (myCharStream\itcast) File destFolder = new File("myCharStream",srcFolderName); //Judge whether the File corresponding to the destination directory exists. If it does not exist, create it if(!destFolder.exists()) { destFolder.mkdir(); } //Get the File array of all files in the data source directory File[] listFiles = srcFolder.listFiles(); //Traverse the File array to get each File object, which is actually the data source File for(File srcFile : listFiles) { //Data source file: e: \ \ itcast \ \ Mn jpg //Get the name of the File object of the data source File (mn.jpg) String srcFileName = srcFile.getName(); //Create a destination File object with the pathname of destination directory + Mn Jpg composition (myCharStream\itcast\mn.jpg) File destFile = new File(destFolder,srcFileName); //Copy file copyFile(srcFile,destFile); } } private static void copyFile(File srcFile, File destFile) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] bys = new byte[1024]; int len; while ((len=bis.read(bys))!=-1) { bos.write(bys,0,len); } bos.close(); bis.close(); } }
1.3 copy multi-level folders [ application ]
1.3. 1 case requirements
- Copy the folder "E:\itcast" to the directory of disk F
1.3. 2 analysis steps
- Create a data source File object with the path E:\itcast
- Create a destination File object with the path F:\
- The write method copies the folder. The parameters are the data source File object and the destination File object
- Determine whether the data source File is a File
Yes file: copy directly, using byte stream
Not a file:
Create the directory at the destination
Traverse the File array of all files in the directory to get each File object
Go back to 3 and continue (recursion)
1.3. 3 code implementation
public class CopyFoldersDemo { public static void main(String[] args) throws IOException { //Create a data source File object with the path E:\itcast File srcFile = new File("E:\\itcast"); //Create a destination File object with the path F:\ File destFile = new File("F:\\"); //The write method copies the folder. The parameters are the data source File object and the destination File object copyFolder(srcFile,destFile); } //Copy folder private static void copyFolder(File srcFile, File destFile) throws IOException { //Determine whether the data source File is a directory if(srcFile.isDirectory()) { //Create a directory under the destination with the same name as the data source File String srcFileName = srcFile.getName(); File newFolder = new File(destFile,srcFileName); //F:\\itcast if(!newFolder.exists()) { newFolder.mkdir(); } //Get the File array of all files or directories under the data source File File[] fileArray = srcFile.listFiles(); //Traverse the File array to get each File object for(File file : fileArray) { //Take the File as the data source File object and recursively call the method of copying the folder copyFolder(file,newFolder); } } else { //Description is a file, directly copied, with byte stream File newFile = new File(destFile,srcFile.getName()); copyFile(srcFile,newFile); } } //Byte buffer stream copy file private static void copyFile(File srcFile, File destFile) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] bys = new byte[1024]; int len; while ((len = bis.read(bys)) != -1) { bos.write(bys, 0, len); } bos.close(); bis.close(); } }
1.4 exception handling of copied documents [ application ]
1.4. 1. Basic practice
public class CopyFileDemo { public static void main(String[] args) { } //try...catch...finally private static void method2() { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("fr.txt"); fw = new FileWriter("fw.txt"); char[] chs = new char[1024]; int len; while ((len = fr.read()) != -1) { fw.write(chs, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fw!=null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } if(fr!=null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Throw processing private static void method1() throws IOException { FileReader fr = new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt"); char[] chs = new char[1024]; int len; while ((len = fr.read()) != -1) { fw.write(chs, 0, len); } fw.close(); fr.close(); } }
1.4.2JDK7 version improvement
public class CopyFileDemo { public static void main(String[] args) { } //Improvement scheme of JDK7 private static void method3() { try(FileReader fr = new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt");){ char[] chs = new char[1024]; int len; while ((len = fr.read()) != -1) { fw.write(chs, 0, len); } } catch (IOException e) { e.printStackTrace(); } } }
1.4.3JDK9 version improvement
public class CopyFileDemo { public static void main(String[] args) { } //Improvement scheme of JDK9 private static void method4() throws IOException { FileReader fr = new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt"); try(fr;fw){ char[] chs = new char[1024]; int len; while ((len = fr.read()) != -1) { fw.write(chs, 0, len); } } catch (IOException e) { e.printStackTrace(); } } }
2.IO special operation flow
2.1 standard input stream [application]
-
There are two static member variables in the System class
- public static final InputStream in: standard input stream. Typically, the stream corresponds to keyboard input or another input source specified by the host environment or the user
- public static final PrintStream out: standard output stream. Typically, the flow corresponds to a display output or another output destination specified by the host environment or the user
-
Own keyboard input data
public class SystemInDemo { public static void main(String[] args) throws IOException { //public static final InputStream in: standard input stream // InputStream is = System.in; // int by; // while ((by=is.read())!=-1) { // System.out.print((char)by); // } //How to convert byte stream to character stream? Convert stream with // InputStreamReader isr = new InputStreamReader(is); // //Can you read one line of data at a time using character stream? sure // //However, the method of reading one line of data at a time is a unique method of character buffered input stream // BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter a string:"); String line = br.readLine(); System.out.println("The string you entered is:" + line); System.out.println("Please enter an integer:"); int i = Integer.parseInt(br.readLine()); System.out.println("The integer you entered is:" + i); //It's too troublesome to enter data by keyboard, so Java provides a class for us to use Scanner sc = new Scanner(System.in); } }
2.2 standard output stream [application]
-
There are two static member variables in the System class
- public static final InputStream in: standard input stream. Typically, the stream corresponds to keyboard input or another input source specified by the host environment or the user
- public static final PrintStream out: standard output stream. Typically, the flow corresponds to a display output or another output destination specified by the host environment or the user
-
The essence of output statement: it is a standard output stream
- PrintStream ps = System.out;
- Some methods of PrintStream class, system Out can be used
-
Sample code
public class SystemOutDemo { public static void main(String[] args) { //public static final PrintStream out: standard output stream PrintStream ps = System.out; //It can easily print various data values //ps.print("hello"); //ps.print(100); //ps.println("hello"); //ps.println(100); //System.out is essentially a byte output stream System.out.println("hello"); System.out.println(100); System.out.println(); //System.out.print(); } }
2.3 byte print stream [ application ]
-
Print stream classification
- Byte print stream: PrintStream
- Character print stream: PrintWriter
-
Characteristics of print stream
- It is only responsible for outputting data, not reading data
- IOException will never be thrown
- Has its own unique method
-
Byte print stream
- PrintStream(String fileName): creates a new print stream with the specified file name
- Use the method of inheriting the parent class to write data, and transcode it when viewing; Use your own unique method to write data and view the output of the data as it is
- You can change the destination of the output statement
public static void setOut(PrintStream out): reassign the standard output stream
-
Sample code
public class PrintStreamDemo { public static void main(String[] args) throws IOException { //PrintStream(String fileName): creates a new print stream with the specified file name PrintStream ps = new PrintStream("myOtherStream\\ps.txt"); //Write data //Some methods of byte output stream //ps.write(97); //Write data using unique methods //ps.print(97); //ps.println(); //ps.print(98); ps.println(97); ps.println(98); //Release resources ps.close(); } }
2.4 character print stream [ application ]
-
Construction method of character print stream
Method name explain PrintWriter(String fileName) Creates a new PrintWriter with the specified file name without automatic refresh PrintWriter(Writer out, boolean autoFlush) Create a new PrintWriter out: character output stream autoFlush: a Boolean value. If true, the println, printf, or format methods will flush the output buffer -
Sample code
public class PrintWriterDemo { public static void main(String[] args) throws IOException { //PrintWriter(String fileName): creates a new PrintWriter with the specified file name without automatic line refresh // PrintWriter pw = new PrintWriter("myOtherStream\\pw.txt"); // pw.write("hello"); // pw.write("\r\n"); // pw.flush(); // pw.write("world"); // pw.write("\r\n"); // pw.flush(); // pw.println("hello"); /* pw.write("hello"); pw.write("\r\n"); */ // pw.flush(); // pw.println("world"); // pw.flush(); //PrintWriter(Writer out, boolean autoFlush): create a new PrintWriter PrintWriter pw = new PrintWriter(new FileWriter("myOtherStream\\pw.txt"),true); // PrintWriter pw = new PrintWriter(new FileWriter("myOtherStream\\pw.txt"),false); pw.println("hello"); /* pw.write("hello"); pw.write("\r\n"); pw.flush(); */ pw.println("world"); pw.close(); } }
2.5 copy Java file print stream improved version [application]
-
Case requirements
- Put printstreamdemo in the module directory Java to Copy.java in the module directory java
-
Analysis steps
- Create character input stream objects from data sources
- Create a character output stream object based on the destination
- Read and write data, copy files
- Release resources
-
code implementation
public class CopyJavaDemo { public static void main(String[] args) throws IOException { /* //Create character input stream objects from data sources BufferedReader br = new BufferedReader(new FileReader("myOtherStream\\PrintStreamDemo.java")); //Create a character output stream object based on the destination BufferedWriter bw = new BufferedWriter(new FileWriter("myOtherStream\\Copy.java")); //Read and write data, copy files String line; while ((line=br.readLine())!=null) { bw.write(line); bw.newLine(); bw.flush(); } //Release resources bw.close(); br.close(); */ //Create character input stream objects from data sources BufferedReader br = new BufferedReader(new FileReader("myOtherStream\\PrintStreamDemo.java")); //Create a character output stream object based on the destination PrintWriter pw = new PrintWriter(new FileWriter("myOtherStream\\Copy.java"),true); //Read and write data, copy files String line; while ((line=br.readLine())!=null) { pw.println(line); } //Release resources pw.close(); br.close(); } }
2.6 object serialization stream [application]
-
Introduction to object serialization
- Object serialization: saving objects to disk or transferring objects over the network
- This mechanism uses a byte sequence to represent an object, which contains information such as object type, object data and attributes stored in the object
- After the byte sequence is written 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 serialization stream: ObjectOutputStream
- Writes the original data type and graph of the Java object to the OutputStream. You can use ObjectInputStream to read (refactor) objects. Persistent storage of objects can be achieved by using streaming files. If the stream is a network socket stream, you can refactor the object on another host or in another process
-
Construction method
Method name explain ObjectOutputStream(OutputStream out) Creates an ObjectOutputStream that writes to the specified OutputStream -
Methods for serializing objects
Method name explain void writeObject(Object obj) Writes the specified object to ObjectOutputStream -
Sample code
- Student class
public class Student implements Serializable { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } 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; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
- Test class
public class ObjectOutputStreamDemo { public static void main(String[] args) throws IOException { //ObjectOutputStream(OutputStream out): creates an ObjectOutputStream that writes to the specified OutputStream ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myOtherStream\\oos.txt")); //create object Student s = new Student("Lin Qingxia",30); //void writeObject(Object obj): writes the specified object to ObjectOutputStream oos.writeObject(s); //Release resources oos.close(); } }
- Student class
-
matters needing attention
- To serialize an object, the class to which the object belongs must implement the Serializable interface
- Serializable is a tag interface that can be implemented without rewriting any methods
2.7 object deserialization stream [application]
-
Object deserialization stream: ObjectInputStream
- ObjectInputStream deserializes raw data and objects previously written using ObjectOutputStream
-
Construction method
Method name explain ObjectInputStream(InputStream in) Creates an ObjectInputStream read from the specified InputStream -
Method of deserializing object
Method name explain Object readObject() Read an object from ObjectInputStream -
Sample code
public class ObjectInputStreamDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { //ObjectInputStream(InputStream in): creates an ObjectInputStream read from the specified InputStream ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myOtherStream\\oos.txt")); //Object readObject(): reads an object from ObjectInputStream Object obj = ois.readObject(); Student s = (Student) obj; System.out.println(s.getName() + "," + s.getAge()); ois.close(); } }
2.8 serialVersionUID & transient [application]
-
serialVersionUID
- After serializing an object with the object serialization stream, if we modify the class file to which the object belongs, will there be a problem reading the data?
- There will be a problem and an InvalidClassException will be thrown
- If something goes wrong, how to solve it?
- Re serialization
- Add a serialVersionUID to the class to which the object belongs
- private static final long serialVersionUID = 42L;
- After serializing an object with the object serialization stream, if we modify the class file to which the object belongs, will there be a problem reading the data?
-
transient
- If the value of a member variable in an object does not want to be serialized, how to implement it?
- The member variable is decorated with the transient keyword. The member variable marked with the keyword does not participate in the serialization process
- If the value of a member variable in an object does not want to be serialized, how to implement it?
-
Sample code
- Student class
public class Student implements Serializable { private static final long serialVersionUID = 42L; private String name; //private int age; private transient int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } 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; } // @Override // public String toString() { // return "Student{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } }
- Test class
public class ObjectStreamDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { // write(); read(); } //Deserialization private static void read() throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myOtherStream\\oos.txt")); Object obj = ois.readObject(); Student s = (Student) obj; System.out.println(s.getName() + "," + s.getAge()); ois.close(); } //serialize private static void write() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myOtherStream\\oos.txt")); Student s = new Student("Lin Qingxia", 30); oos.writeObject(s); oos.close(); } }
- Student class
3.Properties collection
3.1 use of properties as Map set [application]
-
Properties introduction
- Is a collection class of Map system
- Properties can be saved to or loaded from a stream
- Each key in the attribute list and its corresponding value is a string
-
Properties basic usage
public class PropertiesDemo01 { public static void main(String[] args) { //Create collection object // Properties<String,String> prop = new Properties<String,String>(); // error Properties prop = new Properties(); //Storage element prop.put("itheima001", "Lin Qingxia"); prop.put("itheima002", "Zhang Manyu"); prop.put("itheima003", "Wang Zuxian"); //Traversal set Set<Object> keySet = prop.keySet(); for (Object key : keySet) { Object value = prop.get(key); System.out.println(key + "," + value); } } }
3.2 properties as a unique method of Map set [application]
-
Unique method
Method name explain Object setProperty(String key, String value) Set the keys and values of the collection, which are of String type. The bottom layer calls the Hashtable put method String getProperty(String key) Search for attributes using the key specified in this attribute list Set stringPropertyNames() Returns a non modifiable key set from the property list, where the key and its corresponding value are strings -
Sample code
public class PropertiesDemo02 { public static void main(String[] args) { //Create collection object Properties prop = new Properties(); //Object setProperty(String key, String value): sets the key and value of the collection, both of which are of String type. The bottom layer calls the Hashtable put method prop.setProperty("itheima001", "Lin Qingxia"); /* Object setProperty(String key, String value) { return put(key, value); } Object put(Object key, Object value) { return map.put(key, value); } */ prop.setProperty("itheima002", "Zhang Manyu"); prop.setProperty("itheima003", "Wang Zuxian"); //String getProperty(String key): use the key specified in this property list to search for properties //System.out.println(prop.getProperty("itheima001")); //System.out.println(prop.getProperty("itheima0011")); //System.out.println(prop); //Set < string > stringpropertynames(): returns a non modifiable key set from the property list, where the key and its corresponding value are strings Set<String> names = prop.stringPropertyNames(); for (String key : names) { //System.out.println(key); String value = prop.getProperty(key); System.out.println(key + "," + value); } } }
3.3Properties and IO flow [application]
-
Method combined with IO stream
Method name explain void load(InputStream inStream) Read the attribute list (key and element pairs) from the input byte stream void load(Reader reader) Read the attribute list (key and element pairs) from the input character stream void store(OutputStream out, String comments) Write this list of Properties (key and element pairs) to this Properties table and write the output byte stream in a format suitable for using the load(InputStream) method void store(Writer writer, String comments) Write this list of Properties (key and element pairs) to this Properties table and write the output character stream in a format suitable for using the load(Reader) method -
Sample code
public class PropertiesDemo03 { public static void main(String[] args) throws IOException { //Save the data in the collection to a file //myStore(); //Load the data in the file into the collection myLoad(); } private static void myLoad() throws IOException { Properties prop = new Properties(); //void load(Reader reader): FileReader fr = new FileReader("myOtherStream\\fw.txt"); prop.load(fr); fr.close(); System.out.println(prop); } private static void myStore() throws IOException { Properties prop = new Properties(); prop.setProperty("itheima001","Lin Qingxia"); prop.setProperty("itheima002","Zhang Manyu"); prop.setProperty("itheima003","Wang Zuxian"); //void store(Writer writer, String comments): FileWriter fw = new FileWriter("myOtherStream\\fw.txt"); prop.store(fw,null); fw.close(); } }
3.4 number of games [application]
-
Case requirements
- The number guessing game can only be played for 3 times. If you still want to play, you will be prompted that the game trial is over. If you want to play, please recharge (www.itcast.cn)
-
Analysis steps
-
Write a game class, which has a small game of guessing numbers
-
Write a test class. The test class has the main() method, and the following code is written in the main() method:
Read the data from the file to the Properties collection and implement it with the load() method
File already exists: game txt
There is a data value: count=0Get the number of games played through the Properties collection
Judge whether the number of times has reached 3
If you arrive, give a prompt: the game trial is over. If you want to play, please recharge (www.itcast.cn)
If less than 3 times:
Times + 1, write back the file, and use the store() method of Properties to play the game
-
-
code implementation
public class PropertiesTest { public static void main(String[] args) throws IOException { //Read the data from the file to the Properties collection and implement it with the load() method Properties prop = new Properties(); FileReader fr = new FileReader("myOtherStream\\game.txt"); prop.load(fr); fr.close(); //Get the number of games played through the Properties collection String count = prop.getProperty("count"); int number = Integer.parseInt(count); //Judge whether the number of times has reached 3 if(number >= 3) { //If you arrive, give a prompt: the game trial is over. If you want to play, please recharge (www.itcast.cn) System.out.println("The game trial has ended. Please recharge if you want to play(www.itcast.cn)"); } else { //play a game GuessNumber.start(); //Times + 1, write back the file and use the store() method of Properties number++; prop.setProperty("count",String.valueOf(number)); FileWriter fw = new FileWriter("myOtherStream\\game.txt"); prop.store(fw,null); fw.close(); } } }