1.IO flow case
1.1 Collection to File Data Sorting Improvement Edition [Application]
1.1.1 Case Requirements
- Keyboard input 5 student information (name, Chinese score, math score, English score). Write text files from high to low according to the total score.
- Format: Name, Chinese, Mathematics, English Examples: Lin Qingxia, 98, 99, 100
1.1.2 Analysis steps
- Defining student classes
- Create a TreeSet collection and sort it by comparator sort
- Keyboard Entry Student Data
- Create Student object and assign the data input by keyboard to the member variables of student object.
- Adding Student Objects to TreeSet Collection
- Create character buffer output stream object
- Traverse the set to get each student object
- Stitching data from student objects into strings in specified formats
- Call the method of character buffer output stream object to write data
- Releasing resources
1.1.3 Code Implementation
-
Student category
public class Student { // Full name private String name; // grade scores of Chinese private int chinese; // Mathematical Achievements private int math; // English Achievements 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 it by comparator sort TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { //Total score ranges 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; } }); //Keyboard Entry Student Data for (int i = 0; i < 5; i++) { Scanner sc = new Scanner(System.in); System.out.println("Please enter _____________" + (i + 1) + "Student Information:"); System.out.println("Full name:"); String name = sc.nextLine(); System.out.println("Language Achievements:"); int chinese = sc.nextInt(); System.out.println("Mathematics Achievements:"); int math = sc.nextInt(); System.out.println("English Achievements:"); int english = sc.nextInt(); //Create Student object and assign the data input by keyboard to the member variables of student object. Student s = new Student(); s.setName(name); s.setChinese(chinese); s.setMath(math); s.setEnglish(english); //Adding Student Objects to TreeSet Collection ts.add(s); } //Create character buffer output stream object BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\ts.txt")); //Traverse the set to get each student object for (Student s : ts) { //Stitching data from student objects into strings in specified formats //Format: Name, Chinese Achievement, Mathematics Achievement, English Achievement 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 buffer output stream object to write data bw.write(sb.toString()); bw.newLine(); bw.flush(); } //Releasing 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 the File object of the data source directory with the path E: itcast
-
Get the name of the File object in the data source directory
-
Create the destination directory File object, and the path consists of (module name + name obtained in step 2)
-
Determine whether the File created in Step 3 exists or not, and if it does not, create it
-
Gets a File array of all files in the data source directory
-
Traversing through the File array, you get each File object, which is actually a data source file.
-
Get the name of the File object of the data source file
-
Create the destination file File object, and the path consists of (destination directory + name obtained in step 7)
-
Copy files
Because it is not clear what types of files are in the data source directory, byte streams are used to copy files.
Constructing Method with File Parameter
1.2.3 Code Implementation
public class CopyFolderDemo { public static void main(String[] args) throws IOException { //Create the File object of the data source directory 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 the destination directory File object with the path name of the module + itcast (myCharStream\\ itcast) File destFolder = new File("myCharStream",srcFolderName); //Determine whether the File corresponding to the destination directory exists, and if it does not, create it if(!destFolder.exists()) { destFolder.mkdir(); } //Gets a File array of all files in the data source directory File[] listFiles = srcFolder.listFiles(); //Traversing through the File array, you get each File object, which is actually a data source file. for(File srcFile : listFiles) { //Data source file: E:\itcastmn.jpg //Get the name of the File object of the data source file (mn.jpg) String srcFileName = srcFile.getName(); //Create the destination file File object with the path name of the destination directory + mn.jpg (myCharStream\\\\\ itcast\ mn.jpg) File destFile = new File(destFolder,srcFileName); //Copy files 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 Multilevel Folder [Application]
1.3.1 Case Requirements
- Copy the folder "E: itcast" to the F-disk directory
1.3.2 Analysis steps
-
Create a data source File object with the path E: itcast
-
Create the destination File object with the path F::\
-
Writing implements folder replication with parameters of data source File object and destination File object
-
Determine whether the data source File is a file
File: Direct copy, byte stream
Not documents:
Create the directory under the destination Traverse through the File array to get all the files in the directory and 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 the destination File object with the path F::\ File destFile = new File("F:\\"); //Writing implements folder replication with parameters of data source File object and destination File object copyFolder(srcFile,destFile); } //Copy folders 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 with the same name as the data source File under the destination String srcFileName = srcFile.getName(); File newFolder = new File(destFile,srcFileName); //F:\\itcast if(!newFolder.exists()) { newFolder.mkdir(); } //Get File arrays 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) { //Using the File as the data source File object, recursively invoke the method of replicating folders copyFolder(file,newFolder); } } else { //The instructions are files, direct copies, byte streams 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 Files [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(); } } } } //Throwout disposal 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.2 JDK7 Version Improvement
public class CopyFileDemo { public static void main(String[] args) { } //Improvement 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.3 JDK9 Version Improvement
public class CopyFileDemo { public static void main(String[] args) { } //Improvement 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 Operational Flow
2.1 Standard Input Flow [Application]
-
There are two static member variables in the System class
- Public static final Input Stream in: Standard input stream. Usually the stream corresponds to a keyboard input or another input source specified by the host environment or user.
- Public static final Print Stream out: Standard output stream. Usually the stream corresponds to a display output or another output target specified by the host environment or user.
-
Implementing Keyboard Data Entry by Oneself
public class SystemInDemo { public static void main(String[] args) throws IOException { //Public static final Input Stream 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? Using Conversion Flow // InputStreamReader isr = new InputStreamReader(is); // // Can you read a row of data at a time using character streams? Sure // // However, the way to read one row at a time is a unique way to buffer the input stream of characters. // BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("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 cumbersome to implement keyboard data entry by ourselves, 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 Input Stream in: Standard input stream. Usually the stream corresponds to a keyboard input or another input source specified by the host environment or user.
- Public static final Print Stream out: Standard output stream. Usually the stream corresponds to a display output or another output target specified by the host environment or user.
-
Essence of Output Statements: A Standard Output Stream
- PrintStream ps = System.out;
- PrintStream classes have methods that System.out can use
-
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 print various data values conveniently. // 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 Printing Stream: PrintWriter
-
Characteristics of Print Stream
- Only responsible for output data, not for reading data
- Never throw IOException
- Have your own unique method
-
Byte print stream
-
PrintStream(String fileName): Creates a new print stream using the specified filename
-
Write data by inheriting parent class, and transcode it when viewing; Write data by using its own unique method, and output the data as it is.
-
You can change the destination of the output statement
Public static void setOut (Print Stream out): Reallocation of "standard" output streams
-
-
Sample code
public class PrintStreamDemo { public static void main(String[] args) throws IOException { //PrintStream(String fileName): Creates a new print stream using the specified filename PrintStream ps = new PrintStream("myOtherStream\\ps.txt"); //Write data //Some methods of byte output stream // ps.write(97); //Write data in a specific way // ps.print(97); // ps.println(); // ps.print(98); ps.println(97); ps.println(98); //Releasing resources ps.close(); } }
2.4 Character Printing Stream [Application]
-
Character Printing Stream Construction Room Method
Method name Explain PrintWriter(String fileName) Create a new PrintWriter with the specified filename without the need for automatic refresh PrintWriter(Writer out, boolean autoFlush) Create a new PrintWriter out: character output stream autoFlush: a Boolean value, println, printf, or format method to refresh the output buffer if true -
Sample code
public class PrintWriterDemo { public static void main(String[] args) throws IOException { //PrintWriter(String fileName): Create a new PrintWriter using the specified filename without the need for 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 Improvement Edition [Application]
-
Case requirements
- Copy PrintStreamDemo.java from the module directory to Copy.java from the module directory
-
Analysis steps
- Creating character input stream objects from data sources
- Create character output stream objects based on destination
- Read and write data, copy files
- Releasing resources
-
code implementation
public class CopyJavaDemo { public static void main(String[] args) throws IOException { /* //Creating character input stream objects from data sources BufferedReader br = new BufferedReader(new FileReader("myOtherStream\\PrintStreamDemo.java")); //Create character output stream objects based on 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(); } //Releasing resources bw.close(); br.close(); */ //Creating character input stream objects from data sources BufferedReader br = new BufferedReader(new FileReader("myOtherStream\\PrintStreamDemo.java")); //Create character output stream objects based on 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); } //Releasing resources pw.close(); br.close(); } }
2.6 Object Serialization Stream [Application]
-
Introduction to Object Serialization
- Object serialization: Save objects to disk or transfer objects over the network
- This mechanism uses a sequence of bytes to represent an object, which contains information such as the type of the object, the data of the object and the properties stored in the object.
- When a sequence of bytes is written to a file, it is equivalent to persisting the information of an object in the file.
- Conversely, the byte sequence can be read back from the file, reconstructed, and deserialized.
-
Object serialization stream: ObjectOutput Stream
- Write the original data types and graphics of Java objects to OutputStream. ObjectInputStream can be used to read (refactor) objects. Persistent storage of objects can be achieved by using streamed files. If the stream is a network socket stream, objects can be reconstructed on another host or in another process
-
Construction method
Method name Explain ObjectOutputStream(OutputStream out) Create an ObjectOutputStream written to the specified OutputStream -
Method of serializing objects
Method name Explain void writeObject(Object obj) Writes the specified object to ObjectOutputStream -
Sample code
-
Student category
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 { //Object Output Stream (Output Stream out): Create an Object Output Stream written to the specified Output Stream 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); //Releasing resources oos.close(); } }
-
-
Matters needing attention
- To serialize an object, the class to which it belongs must implement the Serializable interface
- Serializable is a markup interface that is implemented without rewriting any method
2.7 Object Deserialization Stream [Application]
-
Object deserialization stream: ObjectInputStream
- ObjectInputStream deserializes raw data and objects previously written in ObjectOutputStream
-
Construction method
Method name Explain ObjectInputStream(InputStream in) Create ObjectInputStream read from the specified InputStream -
Method of Deserializing Objects
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): Creates ObjectInputStream read from the specified InputStream ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myOtherStream\\oos.txt")); //Object readObject(): Read an object from ObjectInputStream Object obj = ois.readObject(); Student s = (Student) obj; System.out.println(s.getName() + "," + s.getAge()); ois.close(); } }
2.8 Serial Version UID & Transit [Application]
-
serialVersionUID
- After serializing an object with an object serialization stream, if we modify the class file to which the object belongs, will there be any problem in reading the data?
- Problem will occur and an InvalidClassException exception will be thrown
- If something goes wrong, how can we solve it?
- Reserialization
- Add a serialVersionUID to the class to which the object belongs
- private static final long serialVersionUID = 42L;
- After serializing an object with an object serialization stream, if we modify the class file to which the object belongs, will there be any problem in reading the data?
-
transient
- What if the value of a member variable in an object does not want to be serialized?
- The member variable is modified with a transient keyword, and the member variable marked by the keyword does not participate in the serialization process.
- What if the value of a member variable in an object does not want to be serialized?
-
Sample code
-
Student category
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(); } //Deserialize 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(); } }
-
3.Properties collection
3.1 Use of Properties as Map Sets [Applications]
-
Introduction to Properties
- Is a set class of Map system
- Properties can be saved in or loaded from a stream
- Each key and its corresponding value in the property list is a string
-
Basic Use of Properties
public class PropertiesDemo01 { public static void main(String[] args) { //Creating Collection Objects // Properties < String, String > prop = new Properties < String, String >(); //Error Properties prop = new Properties(); //Storage elements prop.put("itheima001", "Lin Qingxia"); prop.put("itheima002", "Zhang Manyu"); prop.put("itheima003", "Wang Zuxian"); //Ergodic 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 Special Method of Map Set [Application]
-
Unique method
Method name Explain Object setProperty(String key, String value) Setting the keys and values of the collection is of String type, and the underlying call to the Hashtable method put String getProperty(String key) Search for properties using the key specified in this property list Set stringPropertyNames() Returns an unmodifiable key set from the list of attributes, where the key and its corresponding value are strings -
Sample code
public class PropertiesDemo02 { public static void main(String[] args) { //Creating Collection Objects Properties prop = new Properties(); //Object setProperty(String key, String value): Set the key and value of the collection, both String types, and call the Hashtable method put at the bottom 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): Search for properties using the key specified in this property list // System.out.println(prop.getProperty("itheima001")); // System.out.println(prop.getProperty("itheima0011")); // System.out.println(prop); //Set < String > string Property Names (): Returns an unmodifiable key set from the list of attributes, 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.3 P roperties and IO flow method [application]
-
Method of Combining with IO Flow
Method name Explain void load(InputStream inStream) Read the list of attributes (key and element pairs) from the input byte stream void load(Reader reader) Read the list of attributes (key and element pairs) from the input character stream void store(OutputStream out, String comments) Write the list of attributes (key and element pairs) into the Properties table to write the output byte stream in a format suitable for using the load(InputStream) method void store(Writer writer, String comments) Write the list of attributes (key and element pairs) into the Properties table to 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 data in a collection to a file // myStore(); //Loading data from a file into a 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 Game Number Cases [Application]
-
Case requirements
- If you want to play it again, you can only try it three times. Tip: The game is over, if you want to play it, please recharge it (www.itcast.cn)
-
Analysis steps
-
Write a game class with a guessing game
-
Write a test class with the main() method and the main() method with the following code:
Read data from file to Properties collection, and implement it by load()
The file already exists: game.txt There is a data value: count=0
Get the number of games played through the Properties collection
Judge whether the number of times has reached three
If so, give a hint: the game trial is over, if you want to play, please recharge (www.itcast.cn) If not three times: Number of times + 1, rewrite the file, and use the store() method of Properties to play games
-
-
code implementation
public class PropertiesTest { public static void main(String[] args) throws IOException { //Read data from file to Properties collection, and implement it by 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 three if(number >= 3) { //If so, give a hint: the game trial is over, if you want to play, please recharge (www.itcast.cn) System.out.println("Game trial is over, please recharge if you want to play.(www.itcast.cn)"); } else { //Play a game GuessNumber.start(); //Number of times + 1, rewrite back to the file, using the store() method of Properties to achieve number++; prop.setProperty("count",String.valueOf(number)); FileWriter fw = new FileWriter("myOtherStream\\game.txt"); prop.store(fw,null); fw.close(); } } }