1 API
1.1 Api document download
1.API (Application Programming Interface) is the basic programming interface provided by Java. Everything that can be called is API.
2.Java language provides a large number of basic classes, so Oracle also provides corresponding API documents for these basic classes to tell developers how to use these classes and the methods contained in these classes.
3. Download API:
Additional resources Java se 8 Documentation download.
http://www.oracle.com/technetwork/java/javase/downloads/index.html
4. See: download install configure of Api of JDK8 version for details doc
1.2 common categories
1.3 Object
1.3.1 concept
-
The Object class is the root parent of all Java classes
-
If the extension keyword is not used in the declaration of a class to indicate its parent class, the default parent class is Java Lang.Object class
-
The properties and methods in the Object class have generality.
Attribute: None
Methods: equals() / toString() / getClass() /hashCode() / clone() / finalize() / wait() / notify() / notifyAll()
Construction method: the Object class only declares a constructor with an empty parameter
-
The Object class exists in Java In the lang package, we do not need to manually import the lang package
1.3.2 method explanation in object
//1.clone() is not commonly used. When you use it, you are looking for information. It is not explained here. protected Object clone() Create and return a copy of this object //2. Explain at this time. boolean equals(Object obj) Indicates whether some other object is "equal" to this object. String toString() Returns a string representation of the object. //3. The remaining methods will be discussed in subsequent reflection, collection and thread communication. int hashCode() Returns the hash code value of the object. protected void finalize() This method is called by the object's garbage collector when the garbage collector determines that there are no more references to the object. Class<?> getClass() Return to this Object Runtime class. ......
1.3.3 difference between = = and equals
EqualsTest class:
package com.atguigu.java1; import java.util.Date; /* * * Interview question: = = what's the difference between equals * * 1, Review the use of = =: * == : operator * 1. It can be used in basic data type variables and reference data type variables * 2. If you are comparing variables of basic data type: compare whether the data saved by the two variables are equal. (not necessarily the same type) * If you are comparing variables of reference data type: compare whether the address values of the two objects are the same That is, whether two references point to the same object entity * Supplement: = = when the symbol is used, the variable types on the left and right sides of the symbol must be consistent. (note that it refers to consistency rather than the same. For example, both numeric types, int and double can be compared, while int and boolean cannot be compared) * * 2, Use of equals() method: * 1. Is a method, not an operator * 2. It can only be applied to reference data types (explanation: all methods are called through the object name. The method name () is the reference data type, and the basic type cannot call the method, unless the wrapper class) * 3. Object Definition of equals() in class: * public boolean equals(Object obj) { return (this == obj); } * Note: equals() and = = defined in the Object class have the same function: compare whether the address values of the two objects are the same That is, whether two references point to the same Object entity * * 4. String, Date, File, wrapper class, etc. all override the equals() method in the Object class. After rewriting, the comparison is not * Whether the addresses of the two references are the same, but whether the "entity content" of the two objects is the same. * * 5. In general, if we use equals() in our custom class, we usually compare whether the "entity content" of the two objects is the same. So, we * You need to rewrite the equals() in the Object class (it can be written by yourself or automatically generated by development tools such as eclipse, right-click -- source...) * Rewriting principle: compare whether the entity contents of two objects are the same * 6.Precautions: 1 x. Equals (null) returns false in any case, * 2.null.equals(y) You can't write like this. It will report a null pointer exception. Therefore, when x.equals(y) judges equals, it is best to judge whether x is null first * Ratio down when not Null. If the following y is an explicit string, such as abc, you can write the determined string to the front to avoid Null pointer exception. * For example: * public class Student extends Person { public static void main(String[] args) { System.out.println("Please enter the string name: "); String name= new Scanner(System.in).nextLine(); System.out.println("Judge whether the saved value of the input string name is Tom: "); //if(name.equals("Tom")){There is a risk that if the name is null, a null pointer will be reported if("Tom".equals(name)){//Modify to: put the determined string in front, so as to ensure that it will not become null (y) , avoid null pointers. System.out.println("name The value of is Tom ""); }else { System.out.println("name Value is not Tom '); } } */ public class EqualsTest { public static void main(String[] args) { //Basic data type int i = 10; int j = 10; double d = 10.0; System.out.println(i == j);//true System.out.println(i == d);//true boolean b = true; // System.out.println(i == b); char c = 10; System.out.println(i == c);//true char c1 = 'A'; char c2 = 65; System.out.println(c1 == c2);//true //Reference type: Customer cust1 = new Customer("Tom",21); Customer cust2 = new Customer("Tom",21); System.out.println(cust1 == cust2);//false String str1 = new String("atguigu"); String str2 = new String("atguigu"); System.out.println(str1 == str2);//false System.out.println("****************************"); System.out.println(cust1.equals(cust2));//false--->true System.out.println(str1.equals(str2));//true Date date1 = new Date(32432525324L); Date date2 = new Date(32432525324L); System.out.println(date1.equals(date2));//true } }
Customer class:
package com.atguigu.java1; public class Customer { private String name; private int 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; } public Customer() { super(); } public Customer(String name, int age) { super(); this.name = name; this.age = age; } //1.1 automatically generated equals() through the tool (eclipse tool: right click -- source...) @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Customer other = (Customer) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } //Rewriting principle: compare whether the entity contents (i.e. name and age) of two objects are the same //1.2 rewrite equals() manually // @Override // public boolean equals(Object obj) { // System.out.println("Customer equals()...."); // if (this == obj) { // return true; // } // // if(obj instanceof Customer){ // Customer cust = (Customer)obj; // //Compare whether each attribute of two objects is the same if(this.age == cust.age && this.name.equals(cust.name)){ return true; }else{ return false; } // // //Or // return this.age == cust.age && this.name.equals(cust.name); // }else{ // return false; // // } // // } //2.1 manual implementation // @Override // public String toString() { // return "Customer[name = " + name + ",age = " + age + "]"; // } //2.2 automatic implementation (eclipse tool: right click -- source...) @Override public String toString() { return "Customer [name=" + name + ", age=" + age + "]"; } }
1.3.4 toString
package com.atguigu.java1; import java.util.Date; /* * Object Use of toString() in class: * * 1. When we output a reference to an object, we actually call the toString() of the current object * * 2. Object Definition of toString() in class: * public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } * * 3. String, Date, File, wrapper class, etc. all override the toString() method in the Object class. * This enables the "entity content" information to be returned when the toString() of the object is called * * 4. Custom classes can also override the toString() method. When this method is called, it returns the "entity content" of the object (handwritten by yourself or automatically generated by eclipse tools) */ public class ToStringTest { public static void main(String[] args) { Customer cust1 = new Customer("Tom",21); System.out.println(cust1.toString());//com.atguigu.java1.Customer@15db9742-->Customer[name = Tom,age = 21] System.out.println(cust1);//com. atguigu. java1. Customer@15db9742 -->Output Customer[name = Tom,age = 21] after rewriting String str = new String("MM"); System.out.println(str);//MM Date date = new Date(4534534534543L); System.out.println(date.toString());//Mon Sep 11 08:55:34 GMT+08:00 2113 } }
1.4 String
1.4.1 inheritance
--
;
1.4.2 features
public final class String: String is final and cannot be inherited.
private final char value []: the bottom layer of String maintains a char [], the length of the array cannot be changed, and it is final modified, and the value of the array cannot be modified. --- In other words, the String is a constant and cannot be modified once defined.
1.4.3 creating a String object
Method 1: literal creation
- Syntax: String s1 = "abc"// Definition of literal quantity
- If you are using a string for the first time, java will create an object in the string constant pool.
- Create objects directly in the constant pool (char []) in essence. If you use the same content again, you will find existing objects in the constant pool instead of creating new ones. (reduce memory overhead)
Test:
Note: there are different storage methods in different versions of jvm virtual machine: jdk1 6 and jdk1 The version constant pool of 8 is in the method area, jdk1 7 constant pool in heap.
/* String:String, represented by a pair of "". 1.String Declared final and cannot be inherited 2.String The Serializable interface is implemented: it means that the string supports serialization. The Comparable interface is implemented: it means that the String can compare the size 3.String final char[] value is internally defined to store string data 4.String:Represents an immutable sequence of characters. Abbreviation: non variability. Embodiment: 1 When the string is re assigned, the assigned memory area needs to be rewritten (the address value has changed), and the original value cannot be used for assignment. 2. When connecting an existing string, you also need to assign a value to the memory area again. The original value cannot be used for assignment. 3. When you call the replace() method of String to modify the specified character or String, you also need to reassign the memory area assignment, and the original value cannot be used for assignment. Summary: create a String literally. Once the content in the String changes, it means that a new String has been created and the address value has changed. 5.Assign a value to a string by literal means (different from new). At this time, the string value is declared in the string constant pool. 6.Strings with the same content will not be stored in the string constant pool. */ @Test public void test1(){ String s1 = "abc";//Definition of literal quantity String s2 = "abc"; s1 = "hello";//Because String is an array of char type modified by final, once re assigned, it indicates that a new String has been created, that is, the address value has changed. System.out.println(s1 == s2);// Compare the address values of s1 and s2 System.out.println(s1);//hello System.out.println(s2);//abc System.out.println("*****************"); String s3 = "abc"; s3 += "def"; System.out.println(s3);//abcdef System.out.println(s2); System.out.println("*****************"); String s4 = "abc"; String s5 = s4.replace('a', 'm'); System.out.println(s4);//abc System.out.println(s5);//mbc }
Mode 2: new + constructor mode
Syntax:
First: //Essentially this value = new char[0]; String s1 = new String(); Second: //this.value = original.value; String s2 = new String(String original); Third: //this.value = Arrays.copyOf(value, value.length); String s3 = new String(char[] a); Fourth: String s4 = new String(char[] a,int startIndex,int count); ......There are many more. Please check for details Api.
Test:
/* String Instantiation method: Method 1: through literal definition Mode 2: through new + constructor Interview question: String s = new String("abc"); How many objects are created in memory? Two: one is the new structure in the heap space, and the other is the data in the constant pool corresponding to char []: "abc" */ @Test public void test2(){ //Through literal definition: at this time, the data javaEE of s1 and s2 is declared in the string constant pool in the method area. String s1 = "javaEE"; String s2 = "javaEE"; //Through the new + constructor: the address values saved in s3 and s4 at this time are the corresponding address values after the data opens up space in the heap space. String s3 = new String("javaEE"); String s4 = new String("javaEE"); System.out.println(s1 == s2);//true System.out.println(s1 == s3);//false System.out.println(s1 == s4);//false System.out.println(s3 == s4);//false System.out.println("***********************"); Person p1 = new Person("Tom",12); Person p2 = new Person("Tom",12); System.out.println(p1.name.equals(p2.name));//true /*Stored procedure: 1 The created objects P1 and P2 are stored in the heap, and the address values of P1 and P2 stacks are different. 2.p1 p2 The value value in the object is the address of the constant pool corresponding to the array of char type, The same value for the constant pool represents P1 name,p2.name has the same address value.*/ System.out.println(p1.name == p2.name);//true p1.name = "Jerry"; System.out.println(p2.name);//Tom }
1.4.3 comparison of different string splicing operations
/* Conclusion: 1.The splicing results of constants and constants are in the constant pool. And constants with the same content will not exist in the constant pool. 2.As long as one of them is a variable, the result is in the heap. 3.If the result of splicing calls the intern() method, the return value is in the constant pool */ @Test public void test4(){ String s1 = "javaEEhadoop"; String s2 = "javaEE"; String s3 = s2 + "hadoop"; System.out.println(s1 == s3);//false final String s4 = "javaEE";//s4: constant String s5 = s4 + "hadoop"; System.out.println(s1 == s5);//true } @Test public void test3(){ String s1 = "javaEE"; String s2 = "hadoop"; String s3 = "javaEEhadoop"; String s4 = "javaEE" + "hadoop"; String s5 = s1 + "hadoop"; String s6 = "javaEE" + s2; String s7 = s1 + s2; System.out.println(s3 == s4);//true System.out.println(s3 == s5);//false System.out.println(s3 == s6);//false System.out.println(s3 == s7);//false System.out.println(s5 == s6);//false System.out.println(s5 == s7);//false System.out.println(s6 == s7);//false String s8 = s6.intern();//Return the "Java EE Hadoop" that already exists in the constant value used by s8 System.out.println(s3 == s8);//true }
1.4.4 common methods
char charAt(int index) index Index (i.e. subscript, the bottom layer is array) Returns the at the specified index char Value. String concat(String str) Concatenates the specified string to the end of this string. boolean contains(CharSequence s) If and only if this string contains the specified char Value sequence, return true. boolean endsWith(String suffix) Tests whether this string ends with the specified suffix. boolean equals(Object anObject) Compares this string with the specified object. byte[] getBytes() Use the specified character set to convert this String Code as byte Sequence and store the results in a new byte Array. int indexOf(String str) Returns the index of the specified substring at the first occurrence in this string. int lastIndexOf(String str) Returns the index of the rightmost occurrence of the specified substring in this string. boolean isEmpty() if and only if length() Return when is 0 true. int length() Returns the length of this string. String replace(char oldChar, char newChar) Returns a new string by using newChar Replace all occurrences in this string oldChar Got it. String[] split(String regex) Splits the string based on the match of the given regular expression. boolean startsWith(String prefix) Tests whether this string starts with the specified prefix. String substring(int beginIndex) Returns a new string, which is a substring of this string. String substring(int beginIndex, int endIndex) Returns a new string, which is a substring of this string. char[] toCharArray() Converts this string to a new character array. String toLowerCase() Use the rules of the default locale to set this String All characters in are converted to lowercase. String toUpperCase() Use the rules of the default locale to set this String All characters in are converted to uppercase. String trim() Returns a copy of a string, ignoring leading and trailing whitespace. static String valueOf(int i) return int The string representation of the parameter.
1.4.5 common test methods
package cn.tedu.api; import java.util.Arrays; //Test String tool class public class Test2_String { public static void main(String[] args) { //1. A char [] is maintained at the bottom of the string, and it is final, that is, the length of the array cannot be changed, and the value in the array cannot be changed, ---- the string is a constant!! char[] c = new char[] {'a','b','c'} ; String s = new String(c) ; // Trigger the parameterized construction of char [] type -- it exists in heap memory String str = "abc" ; // Direct assignment is stored in the constant pool in heap memory -- efficient -- because the same data in the constant pool will only be saved once String str2 = "abc"; System.out.println(str2==str);//true, the same data has the same storage space, and the same address value is in memory System.out.println(s==str);//false, the address value in the heap is different from that in the constant pool //2. Common methods //There is a return value type in front of it, System.out.println( s.charAt(1) ); // Obtain the corresponding characters according to the subscript System.out.println( s.concat("123") );//Splice a custom string at the end of the string System.out.println( s.contains("bc") );//Determines whether the specified string contains System.out.println( s.endsWith("c") );//Determines whether the string ends with the specified suffix System.out.println( s.equals("abc") );//Determines whether the character is equal to the specified string System.out.println( s.indexOf("a") );//Gets the subscript value of the first occurrence of the specified string in s s = "abca"; System.out.println( s.lastIndexOf("a") );//Gets the subscript value of the last occurrence of the specified string in s System.out.println( s.isEmpty() );//Judge whether the string is empty System.out.println( s.length() );//Gets the length of the string System.out.println( s.replace('a', '0') );//Replace old characters with new ones, 0bc0 System.out.println( s.startsWith("ab") );//Determines whether to start with the specified string System.out.println( s.substring(1) );//Intercepts all strings starting at the specified subscript System.out.println( s.substring(0,2) );//From the specified subscript to the end of the specified subscript, intercept the middle segment [0,2) -- including the head but not the tail System.out.println( s.toLowerCase() );//Automatically convert to lowercase System.out.println( s.toUpperCase() );//Auto capitalize s = " ab ca "; System.out.println( s.trim() );//Remove leading and trailing spaces String num=String.valueOf(123);//Used to convert various types of data into String type System.out.println(num+1);//1231 System.out.println("------String to array------"); byte[] bs = s.getBytes();//Put the string data into byte [] System.out.println( Arrays.toString(bs) ); char[] cs = s.toCharArray(); //Put the string data into char [] System.out.println( Arrays.toString(cs) ); s = "a0b0c0"; String[] ss = s.split("0");//Cut the string according to the specified rules System.out.println( Arrays.toString(ss) );//[a, b, c] } }
1.4.6 review: conversion between String, basic data type and packaging class.
/* review: String Conversion with basic data types and wrapper classes. String --> Basic data type and wrapper class: call the static method of wrapper class: parseXxx(str) Basic data type, wrapper class -- > String: call valueOf(xxx) overloaded by String */ @Test public void test1(){ String str1 = "123"; // int num = (int)str1;// FALSE int num = Integer.parseInt(str1); String str2 = String.valueOf(num);//"123" String str3 = num + ""; System.out.println(str1 == str3); }
1.4.7 conversion between string and character array char []
/* String Conversion between and char [] String --> char[]:Call toCharArray() of String char[] --> String:Call the constructor of String */ @Test public void test2(){ String str1 = "abc123"; //Title: a21cb3 char[] charArray = str1.toCharArray(); for (int i = 0; i < charArray.length; i++) { System.out.println(charArray[i]); } char[] arr = new char[]{'h','e','l','l','o'}; String str2 = new String(arr); System.out.println(str2); }
1.4.8 conversion between string and byte array byte []
/* String Conversion between and byte [] Code: String -- > byte []: call getBytes() of string Decoding: byte [] -- > String: call the constructor of String Encoding: String -- > bytes (binary data that can be understood -- > but cannot be understood) Decoding: the reverse process of encoding, byte -- > string (can't understand binary data -- > understand) Note: when decoding, it is required that the character set used for decoding must be consistent with the character set used for encoding, otherwise garbled code will appear. */ @Test public void test3() throws UnsupportedEncodingException { String str1 = "abc123 China"; byte[] bytes = str1.getBytes();//Use the default character set for encoding. System.out.println(Arrays.toString(bytes)); byte[] gbks = str1.getBytes("gbk");//Use gbk character set for encoding. System.out.println(Arrays.toString(gbks)); System.out.println("******************"); String str2 = new String(bytes);//Decode using the default character set. System.out.println(str2); String str3 = new String(gbks); System.out.println(str3);//Garbled code. Cause: the encoding set and decoding set are inconsistent! String str4 = new String(gbks, "gbk"); System.out.println(str4);//There is no garbled code. Reason: the encoding set and decoding set are consistent! }
1.5 StringBuilder/StringBuffer
1.5.1 features
- Encapsulated char [] array
- Is a variable character sequence
- Provides a set of methods that can modify the character content
- append() is often used as a string connection instead of a string
- The default initial capacity of the internal character array is 16: initial capacity of 16 characters
- If it is larger than 16, it will try to expand the size of the new array. The original size of the new array will be doubled + 2. If the capacity is not enough, it will be directly expanded to the required capacity. int newCapacity = value.length * 2 + 2;
- StringBuffer 1.0 debut thread safety, stringbuilder1 5. The outgoing thread is unsafe
- public final class StringBuilder ----- is a final class and cannot be inherited
char[] value ---- the bottom layer still maintains a char [] like a String, but the value can be modified at any time
1.5.2 what are the similarities and differences among string, StringBuffer and StringBuilder?
/* String,StringBuffer,StringBuilder The similarities and differences between the three? String:An immutable sequence of characters; The bottom layer uses final char [] storage StringBuffer:Variable character sequence; jdk1.0 is thread safe and inefficient; The bottom layer uses char [] storage StringBuilder:Variable character sequence; jdk5.0 new, thread unsafe, high efficiency; The bottom layer uses char [] storage Source code analysis: StringBuffer and StringBuilder are expanded in the same way. String str = new String();//char[] value = new char[0]; String str1 = new String("abc");//char[] value = new char[]{'a','b','c'}; StringBuffer sb1 = new StringBuffer();//char[] value = new char[16];The bottom layer creates an array with a length of 16. System.out.println(sb1.length());// sb1.append('a');//value[0] = 'a'; sb1.append('b');//value[1] = 'b'; StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16]; //Question 1 System. out. println(sb2.length());// 3. The output length is the number of storage //Question 2 Capacity expansion: if the underlying array of data to be added cannot hold enough, the underlying array needs to be expanded. By default, the capacity is expanded to 2 times + 2 of the original capacity, and the elements in the original array are copied to the new array. If you need to modify the string frequently during development, how to choose??? First of all: exclude String and consider StringBuffer and StringBuilder, because it is inefficient to create a new String every time it is changed. Second: consider thread safety. If the resources shared by multi-threaded operations have thread safety problems, consider using StringBuffer. Otherwise, it is not multithreaded or multithreaded, but there is no thread safety problem. Use StringBuilder. After that: after the StringBuffer and StringBuilder are created, the default length is 16. When the length is not enough, it needs to be expanded to affect the efficiency. So if you know For the number of characters stored in the trace, it is recommended to use the construction method that knows the length to create the object: StringBuffer(int capacity) StringBuilder(int capacity) */ @Test public void test1(){ StringBuffer sb1 = new StringBuffer("abc"); sb1.setCharAt(0,'m'); System.out.println(sb1); StringBuffer sb2 = new StringBuffer(); System.out.println(sb2.length());//0 }
1.5.3 common methods
Note: the method names and usage in StringBuffer and StringBuilder are the same.
/* StringBuffer Common methods of: StringBuffer append(xxx): Many append() methods are provided for string splicing StringBuffer delete(int start,int end): Delete the contents of the specified location StringBuffer replace(int start, int end, String str): Replace the [start,end) position with str, as long as the start and end positions are left closed and right open. StringBuffer insert(int offset, xxx): Insert xxx at the specified location StringBuffer reverse() : Reverse the current character sequence public int indexOf(String str) Returns the index of the first occurrence of the specified substring in the string. public String substring(int start,int end):Returns a substring of the left closed right open interval from start to end public int length() Returns the length in characters. public char charAt(int n )Returns the char value at the specified index in this sequence. public void setCharAt(int n ,char ch)Sets the character at the given index to ch. Summary: Add: append(xxx) Delete: delete(int start,int end) Change: setcharat (int n, char CH) / replace (int start, int end, string STR) Check: charAt(int n) Insert: insert(int offset, xxx) Length: length(); *Traverse to get content: for() + charAt() / get content directly by toString() */ @Test public void test2(){ StringBuffer s1 = new StringBuffer("abc"); s1.append(1); s1.append('1'); System.out.println(s1); // s1.delete(2,4); // s1.replace(2,4,"hello"); // s1.insert(2,false); // s1.reverse(); String s2 = s1.substring(1, 3); System.out.println(s1); System.out.println(s1.length()); System.out.println(s2); }
1.5.4 efficiency comparison of three strings
/** * About the use of StringBuffer and StringBuilder * * @author shkstart * @create 2019 3:32 PM */ public class StringBufferBuilderTest { /* Compare the efficiency of String, StringBuffer and StringBuilder: Arrange from high to low: StringBuilder > StringBuffer > string */ @Test public void test3(){ //Initial settings long startTime = 0L; long endTime = 0L; String text = ""; StringBuffer buffer = new StringBuffer(""); StringBuilder builder = new StringBuilder(""); //Start comparison startTime = System.currentTimeMillis(); for (int i = 0; i < 20000; i++) { buffer.append(String.valueOf(i)); } endTime = System.currentTimeMillis(); System.out.println("StringBuffer Execution time of:" + (endTime - startTime));//7 startTime = System.currentTimeMillis(); for (int i = 0; i < 20000; i++) { builder.append(String.valueOf(i)); } endTime = System.currentTimeMillis(); System.out.println("StringBuilder Execution time of:" + (endTime - startTime));//4 startTime = System.currentTimeMillis(); for (int i = 0; i < 20000; i++) { text = text + i; } endTime = System.currentTimeMillis(); System.out.println("String Execution time of:" + (endTime - startTime));//1026 }
1.6 string after class exercises (473 episodes)
1.6.1 inversion of string
package com.atguigu.exer; import org.junit.Test; /** * @author shkstart * @create 2019 10:07 am */ public class StringDemo { /* Inverts a string. Inverts the specified part of the string. For example, "abcdefg" is reversed to "abfedcg" Method 1: convert to char [] */ public String reverse(String str,int startIndex,int endIndex){ if(str != null){ char[] arr = str.toCharArray(); for(int x = startIndex,y = endIndex;x < y;x++,y--){ char temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } return new String(arr); } return null; } //Method 2: use String splicing public String reverse1(String str,int startIndex,int endIndex){ if(str != null){ //Part 1 String reverseStr = str.substring(0,startIndex); //Part 2 for(int i = endIndex;i >= startIndex;i--){ reverseStr += str.charAt(i); } //Part 3 reverseStr += str.substring(endIndex + 1); return reverseStr; } return null; } //Method 3: replace String with StringBuffer/StringBuilder public String reverse2(String str,int startIndex,int endIndex){ if(str != null){ StringBuilder builder = new StringBuilder(str.length()); //Part 1 builder.append(str.substring(0,startIndex)); //Part 2 for(int i = endIndex;i >= startIndex;i--){ builder.append(str.charAt(i)); } //Part 3 builder.append(str.substring(endIndex + 1)); return builder.toString(); } return null; } @Test public void testReverse(){ String str = "abcdefg"; String reverse = reverse2(str, 2, 5); System.out.println(reverse); } }
1.6.2 get the number of occurrences of one string in another string
package com.atguigu.exer; import org.junit.Test; /** * @author shkstart * @create 2019 10:26 am */ public class StringDemo1 { /* Gets the number of occurrences of one string in another string. For example, get the number of occurrences of "ab" in "abkkcadkabkebfkaabkskab" */ /** * Gets the number of occurrences of subStr in mainStr * @param mainStr * @param subStr * @return */ public int getCount(String mainStr,String subStr){ int mainLength = mainStr.length(); int subLength = subStr.length(); int count = 0; int index = 0; if(mainLength >= subLength){ //Mode 1: // while((index = mainStr.indexOf(subStr)) != -1){ // count++; // mainStr = mainStr.substring(index + subStr.length()); // } //Mode 2: improvement of mode 1 while((index = mainStr.indexOf(subStr,index)) != -1){ count++; index += subLength; } return count; }else{ return 0; } } @Test public void testGetCount(){ String mainStr = "abkkcadkabkebfkaabkskab"; String subStr = "ab"; int count = getCount(mainStr, subStr); System.out.println(count); } }
1.6.3 get the largest identical substring in two strings
package com.atguigu.exer; import org.junit.Test; import java.util.Arrays; /** * @author shkstart * @create 2019 10:42 am */ public class StringDemo2 { /* Gets the largest identical substring in two strings. For example: str1 = "abcwerthelloyuiodefabcdef";str2 = "cvhellobnm" Tip: compare the short string with the substring whose length decreases in turn with the longer string. */ //Premise: there is only one largest identical substring in the two strings public String getMaxSameString(String str1,String str2){ if(str1 != null && str2 != null){ String maxStr = (str1.length() >= str2.length())? str1 : str2; String minStr = (str1.length() < str2.length())? str1 : str2; int length = minStr.length(); for(int i = 0;i < length;i++){ for(int x = 0,y = length - i;y <= length;x++,y++){ String subStr = minStr.substring(x,y); if(maxStr.contains(subStr)){ return subStr; } } } } return null; } // If there are multiple largest substrings with the same length // At this time, first return String [], and then replace it with ArrayList in the collection, which is more convenient public String[] getMaxSameString1(String str1, String str2) { if (str1 != null && str2 != null) { StringBuffer sBuffer = new StringBuffer(); String maxString = (str1.length() > str2.length()) ? str1 : str2; String minString = (str1.length() > str2.length()) ? str2 : str1; int len = minString.length(); for (int i = 0; i < len; i++) { for (int x = 0, y = len - i; y <= len; x++, y++) { String subString = minString.substring(x, y); if (maxString.contains(subString)) { sBuffer.append(subString + ","); } } // System.out.println(sBuffer); if (sBuffer.length() != 0) { break; } } String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,"); return split; } return null; } @Test public void testGetMaxSameString(){ String str1 = "abcwerthello1yuiodefabcdef"; String str2 = "cvhello1bnmabcdef"; String[] maxSameStrings = getMaxSameString1(str1, str2); System.out.println(Arrays.toString(maxSameStrings)); } }
1.7 use of unit test method
Note: the running program code should be tested in the main method. There are too many codes to distinguish. At this time, the unit test method can be used.
package com.atguigu.java2; import java.util.Date; import org.junit.Test; /* * Java JUnit unit testing in * * Steps: * 1.Select the current project - right click to select: build path - add libraries - JUnit 4 - next * (Optional, this step can also be placed in the fourth step (add dependency and guide package directly) * 2.Create Java classes for unit testing. * At this time, the Java class requires: ① this class is public; ② this class provides a public parameterless constructor * 3.Unit test methods are declared in this class. * Unit test method at this time: the permission of the method is public, with no return value and no formal parameters * * 4.This unit test method needs to declare the annotation: @ test, and import it into the unit test class: import org junit. Test; * * 5.After declaring the unit test method, you can test the relevant code in the method body. * 6.After writing the code, double-click the unit test method name and right-click: run as - JUnit Test * * explain: * 1.If there is no exception in the execution result: green bar * 2.If the execution result is abnormal: red bar */ public class JUnitTest { int num = 10; @Test public void testEquals(){ String s1 = "MM"; String s2 = "MM"; System.out.println(s1.equals(s2)); //Exception of ClassCastException // Object obj = new String("GG"); // Date date = (Date)obj; System.out.println(num); show(); } public void show(){ num = 20; System.out.println("show()...."); } @Test public void testToString(){ String s2 = "MM"; System.out.println(s2.toString()); } }
1.8 packaging
Package the basic types to provide more perfect functions.
1.8.1 correspondence with basic types (note int and char)
1.8.2 parent class of digital type packaging class: Number
Copy the parent class of Abstract: Abstract
Inheritance relationship:
Common methods: (usage is almost the same)
1.8.3 conversion description between basic type, packing class and String class
1.8.4 the basic type and its corresponding packaging type are transferred to each other
package com.cn.ins; import org.junit.Test; /* * Use of packaging: * 1.java Packaging classes corresponding to 8 basic data types are provided, so that the variables of basic data types have the characteristics of classes * * 2.Master: conversion among basic data type, packing class and String */ public class WrapperTest { //Basic data type -- > wrapper class, method 1: call the constructor of wrapper class (obsolete) @Test public void test1(){ int num1 = 10; // System.out.println(num1.toString()); Integer in1 = new Integer(num1); System.out.println(in1.toString());//10 Integer in2 = new Integer("123");//The value passed in can be a number directly or a number of type String System.out.println(in2.toString());//123 //Report exception // Integer in3 = new Integer("123abc"); // System.out.println(in3.toString()); Float f1 = new Float(12.3f); Float f2 = new Float("12.3");//If you want to convert a type into a wrapper class, you must save pure words System.out.println(f1);//12.3 System.out.println(f2);//12.3 Boolean b1 = new Boolean(true); Boolean b2 = new Boolean("TrUe"); System.out.println(b2); //true Boolean b3 = new Boolean("true123");//Type is converted into packaging class. boolean type is optimized. If you want to convert successfully, you don't have to save pure numbers System.out.println(b3);//false Order order = new Order(); System.out.println(order.isMale);//false System.out.println(order.isFemale);//null } /* * Basic data type -- > Packing class, method 2: static integer valueOf(5); Static methods are called by class name. * In the Integer class, there is a cache array in the bottom layer of Integer: it contains 256 Integer cache objects, ranging from - 128 to 127. * When valueOf() is used, objects created in the first use will be cached if they are within the range. If the data of objects created in the second time is the same, * The cache object is accessed first without creating a new one. If you specify a value outside the range, directly create a new object > * * Benefits: create objects within the scope, and create the same data the second time, which will save some space * * Note: only Integer has this effect, and other types have no effect in this range, which is the same as the efficiency of new objects. * In order to facilitate the creation of object unified format, we'd better use the second method. */ @Test public void test11(){ Integer i2 = Integer.valueOf(5) ;//valueOf():2. If the data is efficient between - 128 and 127, the same data will be created only once Integer i3 = Integer.valueOf(5) ; System.out.println(i2==i3);//true uses the same object Integer i4 = Integer.valueOf("5") ; System.out.println(i3==i4);//true, the value can be a number or a string type number } //Wrapper class -- > basic data type: call xxxValue() of wrapper class Xxx @Test public void test2(){ Integer in1 = new Integer(12); int i1 = in1.intValue();//Note that the corresponding is the one previously converted to the wrapper class. System.out.println(i1 + 1); Float f1 = new Float(12.3); float f2 = f1.floatValue(); System.out.println(f2 + 1); } /* * JDK 5.0 New features: automatic packing and automatic unpacking */ @Test public void test3(){ // int num1 = 10; // //Basic data type -- > object of wrapper class // method(num1); //Auto packing: basic data type -- > Packing class int num2 = 10; Integer in1 = num2;//Automatic packing boolean b1 = true; Boolean b2 = b1;//Automatic packing //Automatic unpacking: packaging class -- > basic data type System.out.println(in1.toString()); int num3 = in1;//Automatic unpacking } public void method(Object obj){ System.out.println(obj); } } class Order{ boolean isMale;//The default value becomes false Boolean isFemale;//The default value becomes null }
1.8.5 basic type, and the corresponding packaging class and String type are transferred to each other
Summary:
- Mutual conversion between basic types
- Conversion between reference types
- The basic type and the package type corresponding to the basic type are transferred to each other
- Basic type. The package type and String type corresponding to the basic type are converted to each other.
package com.cn.ins; import org.junit.Test; /* * Use of packaging: * 1.java Packaging classes corresponding to 8 basic data types are provided, so that the variables of basic data types have the characteristics of classes * * 2.Master: conversion among basic data type, packing class and String */ public class WrapperTest { //Basic data type, wrapper class -- > String type: call valueof (xxxxxx) overloaded by String @Test public void test4(){ int num1 = 10; //Mode 1: connection operation String str1 = num1 + ""; //Method 2: call valueof (xxxxxx) of String float f1 = 12.3f; String str2 = String.valueOf(f1);//"12.3" Double d1 = new Double(12.4); String str3 = String.valueOf(d1); System.out.println(str2); System.out.println(str3);//"12.4" } //Wrapper class -- > converted to String type: toString method @Test public void test6(){ Double d1 = new Double(12.4); String d2 = d1.toString(); System.out.println(d2); } //String type -- > basic data type, wrapper class: call parseXxx(String s) of wrapper class @Test public void test5(){ String str1 = "123"; //Error condition: // int num1 = (int)str1; Basic types and reference data types cannot be converted directly // Integer in1 = (Integer)str1; Strong conversion of reference data type, i.e. downward modeling, should have child parent relationship //NumberFormatException may be reported int num2 = Integer.parseInt(str1); System.out.println(num2 + 1);//Must be a pure number String str2 = "true1";//It also has optimization function boolean b1 = Boolean.parseBoolean(str2); System.out.println(b1); } }
1.9 date and time API before jdk8
1.9.1 java.lang.System class
//1. currentTimeMillis() in system class @Test public void test1(){ long time = System.currentTimeMillis(); //Returns the time difference in milliseconds between the current time and 0:0:0:0 on January 1, 1970. //This is called a timestamp System.out.println(time); }
1.9.2 java.util.Date class
/* java.util.Date class |---java.sql.Date class 1.Use of two constructors >Constructor 1: Date(): create a Date object corresponding to the current time >Constructor 2: create a Date object with a specified number of milliseconds 2.Use of two methods >toString():Displays the current year, month, day, hour, minute and second >getTime():Gets the number of milliseconds corresponding to the current Date object. (timestamp) 3. java.sql.Date The database type of. Util corresponds to the date in the database Date >How to instantiate >How to convert Java sql. Date object is converted to Java util. Date object -- polymorphic >How to convert Java util. Date object is converted to Java sql. Date object */ @Test public void test2(){ //Constructor 1: Date(): create a Date object corresponding to the current time Date date1 = new Date(); System.out.println(date1.toString());//Sat Feb 16 16:35:31 GMT+08:00 2019 System.out.println(date1.getTime());//1550306204104 //Constructor 2: create a Date object with a specified number of milliseconds Date date2 = new Date(155030620410L); System.out.println(date2.toString()); //Create Java sql. Date object java.sql.Date date3 = new java.sql.Date(35235325345L); System.out.println(date3);//1971-02-13 only display year, month and day, not hours, minutes and seconds //How to convert Java util. Date object is converted to Java sql. Date object //Case 1: the polymorphic form of new is a subclass of SQL Date, the subclass is assigned to the parent class, which can be polymorphic. // Date date4 = new java.sql.Date(2343243242323L); // java.sql.Date date5 = (java.sql.Date) date4; //Case 2: the direct of new is util Date object, the created object is a parent class, and there is no way to directly create a class. Date date6 = new Date();//The number of milliseconds can be obtained, and sql happens to have a construction method of the number of milliseconds. java.sql.Date date7 = new java.sql.Date(date6.getTime()); }
1.9.3 java.text.SimpleDateFormat class
/** * jdk 8 API test of previous date and time * 1. System Class currentTimeMillis(); * 2. java.util.Date And subclass Java sql. Date * 3. SimpleDateFormat * 4. Calendar * * @author shkstart * @create 2019 11:35 am */ public class DateTimeTest { /* SimpleDateFormat Use of: SimpleDateFormat formatting and parsing of Date class 1.Two operations: 1.1 Format: date -- > string 1.2 Parsing: inverse process of formatting, string -- > date 2.SimpleDateFormat Instantiation of */ @Test public void testSimpleDateFormat() throws ParseException { //Instantiate SimpleDateFormat: use default constructor SimpleDateFormat sdf = new SimpleDateFormat(); //Format: date -- > string Date date = new Date(); System.out.println(date); String format = sdf.format(date); System.out.println(format); //Parsing: inverse process of formatting, string -- > date String str = "19-12-18 11 a.m:43"; Date date1 = sdf.parse(str); System.out.println(date1); //*************Format and parse in the specified way: call the constructor with parameters***************** // SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //format String format1 = sdf1.format(date); System.out.println(format1);//2019-02-18 11:48:27 //Parsing: the string must conform to the format recognized by SimpleDateFormat (reflected by constructor parameters), //Otherwise, throw the exception Date date2 = sdf1.parse("2020-02-18 11:48:27"); System.out.println(date2); } /* Exercise 1: convert the string "2020-09-08" to Java sql. Date Exercise 2: "fishing in three days and drying nets in two days" 1990-01-01 XXXX XX fishing? Drying the net? For example: September 8, 2020? Total days Total days% 5 = = 1,2,3: Fishing Total days% 5 = = 4,0: net drying Calculation of total days? Method 1: (date2. Gettime () - date1 getTime()) / (1000 * 60 * 60 * 24) + 1 Method 2: 1990-01-01 -- > 2019-12-31 + 2020-01-01 -- > 2020-09-08 */ @Test public void testExer() throws ParseException { String birth = "2020-09-08"; SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf1.parse(birth); // System.out.println(date); java.sql.Date birthDate = new java.sql.Date(date.getTime()); System.out.println(birthDate); }
1.9.4 java. util. Calendar Class
/* Calendar Use of calendar class (abstract class) */ @Test public void testCalendar(){ //1. Instantiation //Method 1: create an object of its subclass (Gregorian calendar) //Method 2: call its static method getInstance() Calendar calendar = Calendar.getInstance(); // System.out.println(calendar.getClass()); //2. Common methods //get() returns the value of the given calendar field. int days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //set() sets the given calendar field to the given value. //calendar variability calendar.set(Calendar.DAY_OF_MONTH,22); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); //add() adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar. calendar.add(Calendar.DAY_OF_MONTH,-3); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); //getTime(): Calendar Class -- > date Date date = calendar.getTime(); System.out.println(date); //Settime(): date -- > Calendar Class Date date1 = new Date(); calendar.setTime(date1); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); }
1.10 new date and time API in jdk8
1.10.1 background
@Test public void testDate(){ //If you want to output 2020 9.8, you need to subtract 1900 from the year and 1 from the month, so util Most of the date methods are out of date. Date date1 = new Date(2020 - 1900,9 - 1,8); System.out.println(date1);//Tue Sep 08 00:00:00 GMT+08:00 2020 }
1.10.2 LocalDate,LocalTime,LocalDateTime
/* LocalDate,LocalTime,LocalDateTime Use of explain: 1.LocalDateTime It is used more frequently than LocalDate and LocalTime 2.Similar to Calendar */ @Test public void test1(){ //now(): get the current date, time and date + time LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDate); System.out.println(localTime); System.out.println(localDateTime); //of(): set the specified year, month, day, hour, minute and second. No offset LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43); System.out.println(localDateTime1); //The two methods of instantiating objects are the same //getXxx(): get related properties System.out.println(localDateTime.getDayOfMonth()); System.out.println(localDateTime.getDayOfWeek()); System.out.println(localDateTime.getMonth()); System.out.println(localDateTime.getMonthValue()); System.out.println(localDateTime.getMinute());//Get current minute //Reflect immutability //withXxx(): set related properties LocalDate localDate1 = localDate.withDayOfMonth(22); System.out.println(localDate);//The original date has not changed System.out.println(localDate1);//What changes is the new date LocalDateTime localDateTime2 = localDateTime.withHour(4); System.out.println(localDateTime); System.out.println(localDateTime2); //Immutability LocalDateTime localDateTime3 = localDateTime.plusMonths(3); System.out.println(localDateTime); System.out.println(localDateTime3); LocalDateTime localDateTime4 = localDateTime.minusDays(6); System.out.println(localDateTime); System.out.println(localDateTime4); }
1.10.3 Instant
/* Instant Use of Similar to Java util. Date class */ @Test public void test2(){ //now(): obtain the standard time corresponding to the original meridian, which is 8 hours different from the East eighth District, and solve it through the offset. Instant instant = Instant.now(); System.out.println(instant);//2019-02-18T07:29:41.719Z //The time offset is added, which is equivalent to 8 hours. OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime);//2019-02-18T15:32:50.611+08:00 //Toepochmili(): get the number of milliseconds since 0:0:0 (UTC) on January 1, 1970 -- > getTime() of date class long milli = instant.toEpochMilli(); System.out.println(milli); //Ofepochmili(): get the Instant instance -- > date (long millisecond) by the given number of milliseconds Instant instant1 = Instant.ofEpochMilli(1550475314878L); System.out.println(instant1); }
1.10.4 java.time.format.DateTimeFormatter class
/* DateTimeFormatter:Format or parse date and time Similar to SimpleDateFormat */ @Test public void test3(){ // Method 1: predefined standard format. E.g. ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //Format: date -- > string LocalDateTime localDateTime = LocalDateTime.now(); String str1 = formatter.format(localDateTime); System.out.println(localDateTime); System.out.println(str1);//2019-02-18T15:42:18.797 //Parsing: String -- > date TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797"); System.out.println(parse); // Mode 2: // Localization related formats. For example: ofLocalizedDateTime() // FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDateTime DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); //format String str2 = formatter1.format(localDateTime); System.out.println(str2);//February 18, 2019 03:47:16 PM // Localization related formats. For example: ofLocalizedDate() // FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: applicable to LocalDate DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); //format String str3 = formatter2.format(LocalDate.now()); System.out.println(str3);//2019-2-18 // Key point: Method 3: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS") DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); //format String str4 = formatter3.format(LocalDateTime.now()); System.out.println(str4);//2019-02-18 03:52:09 //analysis TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09"); System.out.println(accessor); }
1.10.5 jdk8 other date and time API s
1.11 Java comparator
Note: it is used to compare the size between objects. In fact, it is based on the attributes between objects.
1.11.1 natural sorting: Java lang.Comparable
CompareTest :
package com.atguigu.java; import org.junit.Test; import java.util.Arrays; import java.util.Comparator; /** * 1, Note: under normal circumstances, objects in Java can only be compared: = = or! =. Cannot use > or < * However, in the development scenario, we need to sort multiple objects. By implication, we need to compare the size of objects. * How? Use either of the two interfaces: Comparable or Comparator * * 2, Comparison between the use of Comparable interface and Comparator: * Comparable Once the interface mode is fixed, ensure that the object of the implementation class of the Comparable interface can be compared in size at any position. * Comparator The interface is a temporary comparison. * * * * *thor shkstart * @create 2019 4:41 PM */ public class CompareTest { /* Comparable Use example of interface: natural sorting 1.For example, String and wrapper classes implement the Comparable interface, rewrite the compareTo(obj) method, and give a way to compare the sizes of two objects. 2.For example, String and wrapper classes are arranged from small to large after rewriting the compareTo() method. (the class provided by the system overrides the compareTo method, and the default is the natural sorting from small to large.) 3. Rules for rewriting compareTo(obj): If the current object this is greater than the formal parameter object obj, a positive integer is returned, If the current object this is less than the formal parameter object obj, a negative integer is returned, If the current object this is equal to the parameter object obj, zero is returned. 4. For custom classes, if sorting is required, we can let the custom class implement the Comparable interface and override the compareTo(obj) method. Indicate how to sort in the compareTo(obj) method */ //1. For Java encapsulated classes, the compareTo method has been rewritten at the bottom. You can directly use the sort method for comparison. // Arrays are: arrays Sort: collections Sort can call the compareTo method. It's just that objects written in custom classes of arrays or collections need to override methods manually. @Test public void test1(){ String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"}; Arrays.sort(arr); System.out.println(Arrays.toString(arr));//[AA, CC, DD, GG, JJ, KK, MM] } //2. Custom class @Test public void test2(){ Goods[] arr = new Goods[5]; arr[0] = new Goods("lenovoMouse",34); arr[1] = new Goods("dellMouse",43); arr[2] = new Goods("xiaomiMouse",12); arr[3] = new Goods("huaweiMouse",65); arr[4] = new Goods("microsoftMouse",43); Arrays.sort(arr);//The sort method will automatically call the rewritten compareTo method. System.out.println(Arrays.toString(arr)); }
Goods:
package com.atguigu.java; /** * Commodity category * @author shkstart * @create 2019 4:52 PM */ public class Goods implements Comparable{ private String name; private double price; public Goods() { } public Goods(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", price=" + price + '}'; } //Specify the way to compare the size of goods: sort according to the price from low to high, and then sort according to the product name from high to low @Override public int compareTo(Object o) { // System.out.println("**************"); if(o instanceof Goods){ Goods goods = (Goods)o; //Mode 1: if(this.price > goods.price){ return 1; //Not necessarily 1, as long as it is a positive number. }else if(this.price < goods.price){ return -1; }else{ // return 0; //this.name is an object of type String. The method provided by the String class itself is from low to high, plus a negative number from high to bottom return -this.name.compareTo(goods.name); } //Method 2: you can directly call the compare method provided by the wrapper class, and the bottom layer rewrites these code steps // return Double.compare(this.price,goods.price); } // return 0; throw new RuntimeException("The data type passed in is inconsistent!"); } }
1.11.2 customized sorting: Java util. Comparator
CompareTest :
package com.atguigu.java; import org.junit.Test; import java.util.Arrays; import java.util.Comparator; /** * 1, Note: under normal circumstances, objects in Java can only be compared: = = or! =. Cannot use > or < * However, in the development scenario, we need to sort multiple objects. By implication, we need to compare the size of objects. * How? Use either of the two interfaces: Comparable or Comparator * * 2, Comparison between the use of Comparable interface and Comparator: * Comparable Once the interface mode is fixed, ensure that the object of the implementation class of the Comparable interface can be compared in size at any position. * Comparator The interface is a temporary comparison. * * * * *thor shkstart * @create 2019 4:41 PM */ public class CompareTest { /* Comparator Interface usage: custom sorting 1.Background: When the element type does not implement Java Lang. comparable interface and inconvenient to modify the code (for example, some classes in jdk are not implemented, but they cannot modify the source code themselves), Or implement Java The collation of lang.comparable interface is not suitable for the current operation, Then consider using Comparator objects to sort 2.Comparison rule: override the compare(Object o1,Object o2) method to compare the sizes of o1 and o2: If the method returns a positive integer, o1 is greater than o2; If 0 is returned, it means equal; Returns a negative integer indicating that o1 is less than o2. */ //Class provided by the system @Test public void test3(){ String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"}; Arrays.sort(arr,new Comparator(){//Call the construction method of sort(xx,xx)2 formal parameters. Here, it is abbreviated as anonymous subclass of anonymous object. //Arrange strings in descending order @Override public int compare(Object o1, Object o2) { if(o1 instanceof String && o2 instanceof String){//After learning anti generics, it can be guaranteed to be a String type without strong conversion String s1 = (String) o1; String s2 = (String) o2; return -s1.compareTo(s2);//compareTo from small to large, plus negative impulse from large to small. } // return 0; throw new RuntimeException("The data type entered is inconsistent"); } }); System.out.println(Arrays.toString(arr)); } //Custom class @Test public void test4(){ Goods[] arr = new Goods[6]; arr[0] = new Goods("lenovoMouse",34); arr[1] = new Goods("dellMouse",43); arr[2] = new Goods("xiaomiMouse",12); arr[3] = new Goods("huaweiMouse",65); arr[4] = new Goods("huaweiMouse",224); arr[5] = new Goods("microsoftMouse",43); Arrays.sort(arr, new Comparator() { //Specify the way to compare the size of goods: sort according to the product name from low to high, and then sort according to the price from high to low @Override public int compare(Object o1, Object o2) { if(o1 instanceof Goods && o2 instanceof Goods){ Goods g1 = (Goods)o1; Goods g2 = (Goods)o2; if(g1.getName().equals(g2.getName())){ return -Double.compare(g1.getPrice(),g2.getPrice()); }else{ return g1.getName().compareTo(g2.getName()); } } throw new RuntimeException("The data type entered is inconsistent"); } }); System.out.println(Arrays.toString(arr)); } }
Goods:
package com.atguigu.java; /** * Commodity category * @author shkstart * @create 2019 4:52 PM */ public class Goods implements Comparable{ private String name; private double price; public Goods() { } public Goods(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", price=" + price + '}'; } //Specify the way to compare the size of goods: sort according to the price from low to high, and then sort according to the product name from high to low @Override public int compareTo(Object o) { // System.out.println("**************"); if(o instanceof Goods){ Goods goods = (Goods)o; //Method 1: write your own comparison rules if(this.price > goods.price){ return 1; }else if(this.price < goods.price){ return -1; }else{ // return 0; return -this.name.compareTo(goods.name); } //Method 2: the comparison rules are written at the bottom of the compare method of the packaging class. You can call the method directly without writing it. // return Double.compare(this.price,goods.price); } // return 0; throw new RuntimeException("The data type passed in is inconsistent!"); } }
1.12 other common categories
1.12.1 System class
package com.atguigu.java; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; /** * Use of other common classes * 1.System * 2.Math * 3.BigInteger BigDecimal * * @author shkstart * @create 2019 6:23 PM */ public class OtherClassTest { @Test public void test1() { String javaVersion = System.getProperty("java.version"); System.out.println("java of version:" + javaVersion); String javaHome = System.getProperty("java.home"); System.out.println("java of home:" + javaHome); String osName = System.getProperty("os.name"); System.out.println("os of name:" + osName); String osVersion = System.getProperty("os.version"); System.out.println("os of version:" + osVersion); String userName = System.getProperty("user.name"); System.out.println("user of name:" + userName); String userHome = System.getProperty("user.home"); System.out.println("user of home:" + userHome); String userDir = System.getProperty("user.dir"); System.out.println("user of dir:" + userDir); }
1.12.2 Math class
1.12.3 BigInteger and BigDecimal
1). BigInteger: it is often used to solve super large integer operations. The usage is the same as 2.
2). BigDecimal: commonly used to solve accurate floating-point operations. The previous operation of ± * / can be optimized into the operation between two objects (decimal: decimal)
Create object:
BigDecimal(double val) -- Pit,Don't use it java Specifies that the definition of floating-point operations is inaccurate BigDecimal(String val) -- This is recommended
Common methods:
BigDecimal add(BigDecimal bd): Do addition BigDecimal substract(BigDecimal bd) : Do subtraction BigDecimal multiply(BigDecimal bd) : Do multiplication BigDecimal divide(BigDecimal bd) : Do Division divide(BigDecimal bd,Reserved digits,Rounding method): Use in case of inexhaustible exception setScale(Reserved digits, rounding method): Ditto (it is) bd1 The number entered, with several digits reserved (rounding method) pow(int n): Find the power of data
Test 1:
Receive the two numbers input by the user and do the operation. package cn.tedu.bigdecimal; import java.math.BigDecimal; import java.util.Scanner; //Floating point solution public class Test1_BigDecimal { public static void main(String[] args) { // method();// Operation with basic types method2();//BigDecimal } private static void method2() { //1. Accept the two decimals entered by the keyboard double a = new Scanner(System.in).nextDouble(); double b = new Scanner(System.in).nextDouble(); //!!! To create BigDecimal object, it is recommended to use the construction method of String parameter!!! The output is accurate only when it is changed into the form of String BigDecimal bd1 = new BigDecimal(a+""); BigDecimal bd2 = new BigDecimal(b+""); //2. Operation BigDecimal bd3 ;//Save calculation results bd3 = bd1.add(bd2);//Addition operation System.out.println(bd3); bd3 = bd1.subtract(bd2);//Subtraction operation System.out.println(bd3); bd3 = bd1.multiply(bd2);//Multiplication System.out.println(bd3); //Division operation, if the division is not complete, will throw an exception Java lang.ArithmeticException // bd3 = bd1.divide(bd2);// Division operation //3 is to keep 3 decimal places, BigDecimal ROUND_ HALF_ The up rounding method is rounding bd3 = bd1.divide(bd2,3,BigDecimal.ROUND_HALF_UP); System.out.println(bd3); } public static void method() { //1. Accept the two decimals entered by the keyboard double a = new Scanner(System.in).nextDouble(); double b = new Scanner(System.in).nextDouble(); //2. Ordinary methods may not be accurate!! eighty-eight billion eight hundred and eighty-eight million eight hundred and eighty-eight thousand eight hundred and eighty-eight System.out.println(a+b); System.out.println(a-b); System.out.println(a*b); System.out.println(a/b); } }
Test 2:
@Test public void test2() { BigInteger bi = new BigInteger("1243324112234324324325235245346567657653"); BigDecimal bd = new BigDecimal("12435.351"); BigDecimal bd2 = new BigDecimal("11"); System.out.println(bi); // System.out.println(bd.divide(bd2)); It's OK to report an error. If you can't, it's OK to report an error if you specify what rules to reserve the number of digits according to. System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));//Division operation, which does not indicate that it is displayed according to the default reserved digits and rounded System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));//Division, 15 digits reserved, rounded }
1.13 expansion
1.13.1 hex
concept
Hexadecimal, also known as carry counting system, is a artificially defined counting method with carry, which is similar to the statistical "positive" word.
For any kind of base system - x base system, it means that the number operation at each position is carried into one digit every X.
Decimal is every decimal one, hexadecimal is every hexadecimal one, binary is every two into one, and so on.
Usually, 1byte=8 binary bits
Therefore, if a number is expressed in binary, it can be expressed as follows: 0000 0000
When these 8 bits are combined, every three bits form octal, and every four bits form hexadecimal.
characteristic
Binary: 0 and 1, two into one, starting with 0b
Octal: 0-7, every eight into one, starting with 0
Decimal system: 0-9, every decimal one
Hexadecimal: 0-9, abcdef, one in every 16, starting with 0x
Binary conversion:
Decimal to binary: continue to divide by 2 quotient 0, take the remainder and write backwards.
Convert decimal 11 to binary: 1011.
Binary to decimal: from the low order, each person is multiplied by the power of 2 and then summed.
Calculate binary data: decimal system corresponding to 0000 1101
Calculate binary data: decimal corresponding to 0110 1110
Binary to octal: starting from the low order, every three digits are a group to generate an octal number, and the highest order is insufficient to fill in zero.
Calculate octal corresponding to binary data 110 0111
Octal to binary: convert a number into three numbers. If it is less than three digits, the highest digit will be filled with zero.
Calculate octal data: binary data corresponding to 023 0653
Binary to hexadecimal: a group of four, converted to a number, starting with 0x
Slightly...
Hexadecimal to binary: one digit becomes four digits
Slightly...
1.13.2 difference of each length
String has a length method. The array has no length method and has a length attribute. There is no length method for the collection, and the size method is used to calculate the length of the collection.
2 IO stream – 01
Usually, three objects are required for File transfer: container (File class) – node stream – processing stream.
Container: an endpoint is required for data reading and writing. Where data is read in, where data is written out. In java, everything is an object, and the File class is this object.
Node flow: the flow directly acting on the File class is called node flow.
Processing stream: a stream directly or indirectly nested on the File class.
2.1 IO introduction
Note 1:
- The reading and writing of data is abstracted into data and flows in the pipeline.
- I ----- > Input: input stream
- O - > output: output stream
- Flow can only flow in one direction
- Data can only be read and written once from beginning to end
- Close flow: there is nothing you can do about physical connections, such as database connection, input / output flow and Socket connection. These resources need to be closed manually.
- All APIs of IO stream come from Java IO package.
Note 2: the input and output of io stream are analyzed from the perspective of memory (program):
- The transfer of persistent data to memory is called an input stream.
- Data transferred from memory to persistent data is called output stream.
2.2 IO classification
-
According to the flow direction of data flow, it is divided into input flow and output flow
-
According to different operation data units, it is divided into byte stream (8 bit) and character stream (16 bit)
Byte stream: suitable for pictures, videos, etc. The data transmission of byte stream is binary data such as 0101.
Character stream: it is applicable to file transmission. The data transmission of character stream is char type characters. You can know what is transmitted. 16bit (bit) = 2byte (byte) = 1 char type character. -
According to the different roles of flow, it can be divided into node flow and processing flow
Node flow / low-level flow: the flow directly acting on the file is called node flow.
Processing flow / high-level flow: Based on the node flow, directly or indirectly package a layer of flow. This external flow is called processing flow and can package multiple.
2.3 inheritance structure
Note: all classes of io stream come from 4 Abstract parent classes.
Note: the dark cells represent commonly used streams. It can be distinguished by suffix
Byte stream: for binary files, it is more widely used to operate all formats of data in the computer. |---InputStream //Abstract parent class of byte input stream |---FileInputStream //File input stream subclass (low level stream / node stream) |---FilterInputStream //Slightly, not commonly used |---BufferedInputStream //Advanced buffer stream / byte input stream processing subclass |---DataInputStream //Data input stream subclass (Advanced stream) |---ObjectInputStream //Deserialize subclasses (create objects without polymorphism) (Advanced stream) |---OutputStream //Byte output stream Abstract parent class |---FileOutputStream //File output stream subclass (low-level stream) |---FilterOutputStream //Slightly, not commonly used |---BufferedOutputStream //Buffer byte output stream subclass (Advanced stream) |---PrintStream //Byte printout stream subclass (Advanced stream) |---DataOutputStream //Data output stream subclass (Advanced stream) |---ObjectOutputStream //Serialize subclasses (create objects without polymorphism) (Advanced stream) Character stream: for text files. Random code is easy to occur in reading and writing. It is best to specify the code set as utf-8, Used to process data in text format txt. |---Reader //Abstract parent class of character input stream |---BufferedReader //Buffered character input stream subclass (Advanced stream) |---InputStreamReader //Input transformation flow (polymorphic can be used) (advanced flow) |---FileReader //Low level character stream (sub stream input class) |---Writer //Character output stream Abstract parent class |---BufferedWriter //Buffered character output stream subclass (Advanced stream) |---OutputStreamWriter //Output conversion stream (polymorphic can be used) (Advanced stream) |---FileWriter //Character output stream subclass (low-level stream / node stream) |---PrintWriter //Character printout stream (Advanced stream)
2.4 use of file class
2.4.1 general
- An object of the File class that represents a File or a File directory (commonly known as a folder)
- The File class is declared in Java Under IO package
- The File class involves the creation, deletion, renaming, modification time, File size and other methods of files or File directories,
The operation of writing or reading the contents of the file is not involved. If you need to read or write the contents of the file, you must use the IO stream to complete it. - Objects of subsequent File classes are often passed as parameters to the stream constructor, indicating the "end point" of reading or writing
2.4.2 construction method instantiation object
Construction method:
Relative path considerations:
1. Ordinary java project: in idea, the relative path of the code written in the unit test method refers to the current Module (under each project). If it is in the main method, it is relative to the current project (the so-called workspace).
2. Ordinary java projects: in eclipse, it is considered that each individual project is a project, so the unit test and main method are relative paths relative to the current project.
Precautions for path separator:
2.4.3 test of construction method
package com.file; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Date; public class FileTest { /* Path separator: each level of directory in the path is separated by a path separator, which is related to the system. windows And DOS system: \, in java, in order to avoid escape characters, it is usually written as \ \ UNIX And URL: /, which is generally supported in windows. In order to solve the problem of path separator in different operating systems, the File class provides a constant, public static final String separator. Provide separators dynamically according to the operating system. */ @Test public void test1(){ //Constructor 1 File file1 = new File("hello.txt");//Relative path: relative to the current module, e: \ idea workspace \ IO File file2 = new File("D:\\workspace_idea1\\JavaSenior\\day08\\he.txt");//Absolute path: because in java, \ single slash represents escape character, use \ \ double slash to represent path separator. System.out.println(file1);//hello.txt System.out.println(file2);//D:\workspace_idea1\JavaSenior\day08\he.txt //Constructor 2: File file3 = new File("D:\\workspace_idea1","JavaSenior"); System.out.println(file3);//D:\workspace_idea1\JavaSenior //Constructor 3: File file4 = new File(file3,"hi.txt"); System.out.println(file4);//D:\workspace_idea1\JavaSenior\hi.txt //Summary: these three constructors create objects. At this time, the toString() method is called, and the output is the object path at the memory level, but there is no corresponding file or file directory on the disk. } }
2.4.4 common test methods
package com.file; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Date; public class FileTest { /* 1: Get function of File class: 1.public String getAbsolutePath(): Get absolute path 2.public String getPath() : Get path 3.public String getName() : Get name 4.public String getParent(): Get the directory path of the upper level file. If none, null is returned 5.public long length() : Gets the length of the file (i.e. the number of characters in bytes. For example, the length of aa is 2). Cannot get the length of the directory. 6.public long lastModified() : Gets the last modification time, in milliseconds The following two methods apply to file directories: 7.public String[] list() : Gets the name array of all files or file directories in the specified directory 8.public File[] listFiles() : Gets the File array of all files or File directories in the specified directory */ @Test public void test2(){ File file1 = new File("hello.txt");//Relative path. When the value is connected to the project, right-click -- - new file File file2 = new File("d:\\io\\hi.txt");//Absolute path //At this time, the method call is only in memory and does not involve disk path. System.out.println(file1.getAbsolutePath());//E:\idea-workspace\IO\hello.txt System.out.println(file1.getPath());//hello.txt System.out.println(file1.getName());//hello.txt System.out.println(file1.getParent());//Null, the existence of the file is still null. It is found according to the relative path. System.out.println(file1.length());//0, because the file does not exist. If it exists, you can get the value. Select item -- right click new file System.out.println(new Date(file1.lastModified()));//Thu Jan 01 08:00:00 CST 1970 System.out.println(); //At this time, the method call is only in memory and does not involve disk path. System.out.println(file2.getAbsolutePath());//d:\io\hi.txt System.out.println(file2.getPath());//d:\io\hi.txt System.out.println(file2.getName());//hi.txt System.out.println(file2.getParent());//d:\io System.out.println(file2.length());//0 System.out.println(file2.lastModified());//0 } //Test file directory: 7,8 @Test public void test3(){ //The disk path must be real to obtain. File file = new File("D:\\workspace_idea1\\JavaSenior"); String[] list = file.list();//Get name array only for(String s : list){ System.out.println(s);//a.txt,aa,b.txt,bb } System.out.println(); File[] files = file.listFiles();//Gets the full path array for(File f : files){ System.out.println(f);//D:\workspace_idea1\JavaSenior\a.txt,D:\workspace_idea1\JavaSenior\b.txt //D:\workspace_idea1\JavaSenior\aa, D:\workspace_idea1\JavaSenior\bb } } /* *2: Rename function of File class: * 9. public boolean renameTo(File dest):Rename the file to the specified file path * For example: file1 Rename to (File2) as an example: * To return true, file1 exists in the hard disk, and file2 cannot exist in the hard disk (path exists, file does not exist). */ @Test public void test4(){ File file1 = new File("hello.txt");//Real existence File file2 = new File("D:\\io\\hi.txt");//Cannot exist boolean renameTo = file1.renameTo(file2); System.out.println(renameTo);//true hello.txt disappear hi Txt is automatically generated, which is equivalent to putting hello Txt file is cut and pasted to the D:\io path and renamed hi txt //Execute again, because file1 is already in file2, so false } /*3: Judgment function of File class: 10.public boolean isDirectory(): Determine whether it is a file directory 11.public boolean isFile() : Determine whether it is a file 12.public boolean exists() : Judge whether it exists 13.public boolean canRead() : Judge whether it is readable 14.public boolean canWrite() : Judge whether it is writable 15.public boolean isHidden() : Determine whether to hide */ @Test public void test5(){ //Relative path File file1 = new File("hello.txt");//The file is real file1 = new File("hello1.txt");//file does not exist System.out.println(file1.isDirectory());//false false System.out.println(file1.isFile());//true false System.out.println(file1.exists());//true false System.out.println(file1.canRead());//true false System.out.println(file1.canWrite());//true false System.out.println(file1.isHidden());//false false System.out.println(); //Absolute path File file2 = new File("d:\\io");//File directory exists //file2 = new File("d:\io1");// File directory does not exist System.out.println(file2.isDirectory());//true false System.out.println(file2.isFile());//false false System.out.println(file2.exists());//true false System.out.println(file2.canRead());//true false System.out.println(file2.canWrite());//true false System.out.println(file2.isHidden());//false false } /* 4: Create the corresponding file or file directory in the hard disk: it is really created in the hard disk 16.public boolean createNewFile() : Create a file. If the file exists, it will not be created and false will be returned 17.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. 18.public boolean mkdirs() : Create a file directory. If this file directory exists, it will not be created. If the upper file directory does not exist, create it together 5: To delete a file or file directory from a disk: 19.public boolean delete(): Delete files or folders Delete precautions: delete in Java does not go to the recycle bin. */ @Test public void test6() throws IOException { File file1 = new File("hi.txt"); if(!file1.exists()){ //File creation file1.createNewFile(); System.out.println("Created successfully"); }else{//File exists file1.delete(); System.out.println("Deleted successfully"); } } @Test public void test7(){ //The creation of the file directory io1 io3 does not exist. If the upper level directory does not contain it, the creation fails. File file1 = new File("d:\\io\\io1\\io3"); boolean mkdir = file1.mkdir(); if(mkdir){ System.out.println("Created successfully 1"); } //io exists, io1, io4 does not exist, and the upper level directory does not contain it. It will help you automatically create the upper level directory. The creation is successful. File file2 = new File("d:\\io\\io1\\io4"); boolean mkdir1 = file2.mkdirs(); if(mkdir1){ System.out.println("Created successfully 2"); } //To delete successfully, the io4 file directory cannot have subdirectories or files File file3 = new File("D:\\io\\io1\\io4"); file3 = new File("D:\\io\\io1"); System.out.println(file3.delete()); } }
2.4.5 exercise 1: recursively calculate the total file size
Recursion: constantly calling the method itself.
Requirement: Statistics file size
1. Encapsulates the specified directory into a File object
2. List the folders
3. Judge. If it is a file, add f.length() directly
4. Judgment: if it is a folder, recursively call the business logic of the method itself and judge again. If it is a file, add it. If it is a folder again, continue the list and judge. If it is a file addition
Note: only files have size, and directories have no size.
package com.file; import java.io.File; public class Test2_File2 { public static void main(String[] args) { // 1. Encapsulate the specified directory into a File object File file = new File("D:\\teach\\a"); int size =count(file);//To use the File path, pass it to that method System.out.println(size); } private static int count(File file) {//File is of type file // 2. List the folders File[] files = file.listFiles();//Gets the File array of all files or File directories in the specified directory //2.1 traverse each resource in the array int sum = 0;//Record file size for (int i = 0; i < files.length; i++) { // 3. Judge. If it is a file, add f.length() directly // files[i] indicates the resources traversed each time if(files[i].isFile()) { sum += files[i].length();//Sum of documents }else if(files[i].isDirectory()){ // 4. Judge, if it is a folder, continue the list, continue to judge, if it is a file addition, if it is a folder again, continue the list, continue to judge, if it is a file addition // 5. If it is a folder, recursively call the business logic of the method itself sum += count(files[i]);//Continue circular judgment and summation of the currently traversed folder } } return sum ; } }
2.4.6 exercise 2: delete folders recursively
Recursion: constantly calling the method itself.
Requirement: delete folder recursively
1. Encapsulate the specified directory into a File object
2. List the folders
3. Judge. If it is a file, delete it directly
4. Judgment: if it is a folder, recursively call the business logic of the method itself and judge again. If it is a file, delete it. If it is a folder, continue to list, continue to judge. If it is a file deletion
Note: to delete successfully, there must be no subdirectories or files in the file directory. Delete in Java does not go to the recycle bin.
package com.file; import java.io.File; import java.util.Scanner; public class Test1_Size { public static void main(String[] args) { System.out.println("Please enter the write path of the file directory you want to delete:"); //1. Receive the folder path entered by the user String path = new Scanner(System.in).nextLine(); File dir = new File(path); //2. Call the specified method to find the size // long max = size(dir); // System.out.println("total folder size is:" + Max "); //i. Call the specified method to delete the folder del(dir); System.out.println("Deleted successfully"); } //ii. New deletion method public static void del(File dir) { //1. List all resources File[] a = dir.listFiles(); //Traverse the array to get each resource for (int i = 0; i < a.length; i++) { //2. Judge whether the resource is a file or a folder if (a[i].isFile()) {//If it is a file, delete it directly a[i].delete(); } else if (a[i].isDirectory()) {//If it is a folder del(a[i]);//Duplicate column resources, duplicate delete files, duplicate judgment is that the folder continues to list resources, delete } } //TODO deleted all the files in the folder. How to delete the empty folder?? dir.delete();//There are no files in the folder. After the for loop, you can delete the empty directory. } }
2.5 byte stream reading
explain:
-
Byte stream is composed of bytes and character stream is composed of characters In Java, a character consists of two bytes Byte stream is the most basic. All subclasses of InputStream and OutputStream are used to process binary data.
-
Streaming transmission mainly refers to parsing the whole audio, video, three-dimensional media and other multimedia files into compressed packets through a specific compression method, and transmitting them sequentially or in real time from the video server to the user's computer. In the system with streaming transmission mode, the user does not have to wait until the whole file is downloaded like the download mode, but can decompress the compressed A/V, 3D and other multimedia files on the user's computer with decompression equipment after a few seconds or tens of seconds of startup delay. At this time, the rest of the multimedia file will continue to download in the server in the background.
InputStream parent class abstract 1.5
Note: this abstract class represents the parent class of all byte input streams. It does not learn its construction method to create objects, but only its common methods.
Common methods:
abstract int read() Reads the next byte of data from the input stream. int read(byte[] b) Note that byte Read a certain number of bytes from the input stream and store them in the buffer array b Yes. int read(byte[] b, int off, int len) Put the input stream at most len Data bytes read in byte Array. void close() //After using the stream, the resource needs to be closed whether it is read in or write out Close this input stream and release all system resources associated with it. ......
2.5.2 FileInputStream subclass (node stream: File byte stream)
Note: insert it directly into the file and read the file data directly.
Create object:
1. FileInputStream(File file) Create a file by opening a connection to the actual file FileInputStream,The file passes through the file system File object file appoint. 2. FileInputStream(FileDescriptor fdObj) By using file descriptors fdObj Create a FileInputStream,The file descriptor represents an existing connection to an actual file in the file system. 3. FileInputStream(String name) Create a file by opening a connection to the actual file FileInputStream,The file is passed through the pathname in the file system name appoint.
Test:
package com.io_file; import org.junit.Test; import java.io.*; /** * Test the use of FileInputStream and FileOutputStream * * Conclusion: * 1. For text files (. txt,.java,.c,.cpp), use character stream processing (because byte stream processing Chinese is garbled) * Note that the garbled code here refers to the garbled code when the data is viewed at the memory level. If it is simply copied from the hard disk -- > hard disk, the text file can still be processed by byte stream. * 2. For non text files (. jpg,.mp3,.mp4,.avi,.doc,.ppt,...), Only byte stream processing can be used (because the basic unit of these non text files is relatively small, and the unit of characters is relatively large, which can not be processed) * * * * @author shkstart * @create 2019 2:13 PM */ public class FileInputOutputStreamTest { //Read the data in the disk into the memory and output it to the console. //When using the byte stream FileInputStream to process text files, there may be garbled codes (in various codes, a byte can store an English character instead of a Chinese character). @Test public void testFileInputStream() { FileInputStream fis = null; try { //1. Documentation File file = new File("hello.txt"); //2. Flow generation fis = new FileInputStream(file); //3. Read data byte[] buffer = new byte[1024];//Note that the byte array is used. The direct size of each read should not be too large or too small. 1024 is the fastest copy speed int len;//Record the number of bytes read each time while((len = fis.read(buffer)) != -1){ String str = new String(buffer,0,len);//Convert byte array to String type System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if(fis != null){ //4. Close resources try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
2.5.3 BufferedInputStream subclass (processing stream: buffered byte stream)
Note: when creating BufferedInputStream, an internal buffer array will be created (the default size is 8M=8*1024). When reading or skipping the bytes in the stream, the internal buffer can be filled again from the included input stream as needed, and multiple bytes can be filled at a time. The function of the cache stream is to improve the reading and writing efficiency.
Create object:
1. BufferedInputStream(InputStream in) Create a BufferedInputStream And save its parameters, that is, the input stream in,For future use. 2. BufferedInputStream(InputStream in, int size) Creates a with the specified buffer size BufferedInputStream And save its parameters, that is, the input stream in,For future use.
Test:
package com.bf_file; import org.junit.Test; import java.io.*; /** * One of the processing streams: the use of buffer streams * * 1.Buffer stream: * BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter * * 2.Function: provide the read and write speed of the stream * The reason for improving the reading and writing speed: a buffer is provided internally (a certain amount of data is read into the buffer and written out at one time) * * 3. Processing flow is "socket connection". Based on the existing flow, the processing flow cannot directly act on the file. * * @author shkstart * @create 2019 2:44 PM */ public class BufferedTest { /* Realize the copy of non text files. A simple copy byte stream can be used for any type of file data */ @Test public void BufferedStreamTest() throws FileNotFoundException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1. Documentation File srcFile = new File("Love and friendship.jpg"); File destFile = new File("Love and friendship 3.jpg"); //2. Flow generation //2.1 node flow FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); //2.2 buffer flow bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3. Copy details: read, write byte[] buffer = new byte[1024]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); // bos.flush();// Refresh buffer: if not called, the default data will be read in and written out after the buffer is full. If the call is shown here, the data may be read in and written out before the buffer is full. } } catch (IOException e) { e.printStackTrace(); } finally { //4. Resource shutdown //Requirements: first close the flow of the outer layer, and then close the flow of the inner layer. The flow sequence of the same level does not matter if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } //Note: when closing the outer layer flow, the inner layer flow will also be closed automatically. The closure of inner laminar flow can be omitted // fos.close(); // fis.close(); } } //Tool Api: a method to realize file replication. A simple copy byte stream can be used for any type of file data public void copyFileWithBuffered(String srcPath,String destPath){ BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1. Documentation File srcFile = new File(srcPath); File destFile = new File(destPath); //2. Flow generation //2.1 node flow FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); //2.2 buffer flow bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3. Copy details: read, write byte[] buffer = new byte[1024]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Resource shutdown //Requirements: first close the flow of the outer layer, and then close the flow of the inner layer if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } //Note: when closing the outer layer flow, the inner layer flow will also be closed automatically. The closure of inner laminar flow can be omitted // fos.close(); // fis.close(); } } @Test public void testCopyFileWithBuffered(){ long start = System.currentTimeMillis(); String srcPath = "D:\\aa\\bb\\01-Shang Silicon Valley-Java Language foundation.avi"; String destPath = "D:\\aa\\bb\\02-Shang Silicon Valley-Java Language foundation.avi"; copyFileWithBuffered(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("The time taken for the copy operation is:" + (end - start));//618 - 176 } }
2.5.4 ObjectInputStream subclass (processing stream: object input stream / deserialization)
Function: it is used to store and read the processing flow of basic data type data or objects (mainly used for objects). Its strength is that it can write objects in Java to the data source and restore objects from the data source.
Noun Description:
- Serialization: the mechanism of using ObjectOutputStream class to save basic type data or objects (convert the information of the object into a string of byte values in a fixed format for output and persist it to disk)
- Deserialization: the mechanism of reading basic type data or objects with ObjectInputStream class (reading serialized data in disk and restoring objects)
Object serialization mechanism: it allows Java objects in memory to be converted into platform independent binary streams, which allows such binary streams to be permanently stored on disk or transmitted to another network node through the network. When other programs get this binary stream, they can restore it to the original Java object.
characteristic:
- Files that need to be serialized must implement the Serializable interface to enable its serialization function.
- Data that does not need to be serialized can be modified as static. Because static belongs to a class, it is not serialized and output with the object.
- Data that does not need to be serialized can also be modified as transient temporary. It exists in memory only during the running of the program and will not be serialized and persisted.
- During deserialization, if it is inconsistent with the serialized version number, deserialization cannot be completed.
- Each serialized file has a unique id. if it is not added, the compiler will calculate and generate a version number according to the class definition information.
- It is often used for data transmission between servers, serialization into files, deserialization and reading data.
- It is often used to pass objects between hosts using socket streams.
Test:
ObjectInputOutputStreamTest class:
package com.io_file; import org.junit.Test; import java.io.*; /** * Use of object streams * 1.ObjectInputStream And ObjectOutputStream * 2.Function: a processing stream used to store and read basic data type data or objects. Its strength is that it can write objects in Java to the data source and restore objects from the data source. * * 3.If you want a Java object to be serializable, you need to meet the corresponding requirements. See person java * * 4.Serialization mechanism: * The object serialization mechanism allows Java objects in memory to be converted into platform independent binary streams, which allows this * The binary stream is permanently stored on disk or transmitted to another network node through the network. * When other programs get this binary stream, they can restore it to the original Java object. * * @author shkstart * @create 2019 10:27 am */ public class ObjectInputOutputStreamTest { /* Serialization process: save java objects in memory to disk or transmit them over the network Implementation using ObjectOutputStream The serialized file is saved in the disk and opened directly. There is garbled code and you can't understand it. If you want to understand it, you can deserialize it to memory and output it to the console for viewing. */ @Test public void testObjectOutputStream(){ ObjectOutputStream oos = null; try { //1. oos = new ObjectOutputStream(new FileOutputStream("object.dat")); //2. oos.writeObject(new String("I Love Beijing Tiananmen "));//System provided object String oos.flush();//Refresh operation oos.writeObject(new Person("Wang Ming",23)); oos.flush(); oos.writeObject(new Person("placed under house arrest",23,1001,new Account(5000))); oos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if(oos != null){ //3. try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* Deserialization: restore the object in the disk file to a java object in memory Using ObjectInputStream to implement */ @Test public void testObjectInputStream(){ ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("object.dat")); Object obj = ois.readObject();//Keep the reading and writing order consistent String str = (String) obj; Person p = (Person) ois.readObject(); Person p1 = (Person) ois.readObject(); System.out.println(str); System.out.println(p); System.out.println(p1); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if(ois != null){ try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Person class:
package com.io_file; import java.io.Serializable; /** * Person The following requirements must be met before serialization * 1.Interface to be implemented: serializable (string implements the serialization interface for the underlying source code of the class provided by the system. Here, the user-defined class needs to implement the serialization interface manually. If the serialization interface is not implemented, an exception will be reported when serializing the object) * Serializable Is to identify the interface: there are no methods and properties in it, which means that all classes that implement this interface can be serialized. * * 2.The current class provides a global constant: serialVersionUID * Question 1: why provide this global variable serialization interface??? * A: because if many files are serialized to the same data source on the disk, they can be clearly restored to the corresponding object according to the serialization id when reading. * Question 2: show the difference between the specified serialization id and the default generated serialization id when changing the member variable??? * Answer: 2.1 show serialization: if the class Person shows that the specified serialization id is 100, then serialize and the generated file is AA Txt to the disk. At this time, modify the member variable of the Person class because it shows serialization, * Therefore, even if the variable value is modified, the serialization id will not change. At this time, the deserialization reads AA according to the serialization id of 100 The data in TXT file can still be restored without modifying member variables * Previous Person object. * 2.2 Automatically generated serialization: if the serialization id automatically generated by the class Person is 100, then serialization is carried out, and the generated file is AA At this time, the txt variable is automatically generated in the disk, because it is modified to the Person class * Therefore, once the member variable is modified, the serialization id will change, assuming that it is 150. At this time, the deserialization id of 150 is not equal to 100, and an exception will be reported if the restore fails. * * * If the class does not display the definition of this serialization id, its value is automatically generated by the Java runtime environment according to the internal details of the class. If the instance variable of the class is modified, the serialVersionUID may change, * This is prone to problems, so it is recommended to explicitly declare. * * * 3.In addition to the Serializable interface that the current Person class needs to implement, all its internal attributes must be guaranteed * Must also be serializable. (by default, the basic data type can be serialized) * * * Supplement: ObjectOutputStream and ObjectInputStream cannot serialize member variables decorated with static and transient * In the later transmission, it is generally not directly transmitted to person, but converted to json for transmission, and json is essentially a special format string. * * @author shkstart * @create 2019 10:38 am */ public class Person implements Serializable{ public static final long serialVersionUID = 475463534532L; private String name; private int age; private int id; private Account acct; public Person(String name, int age, int id) { this.name = name; this.age = age; this.id = id; } public Person(String name, int age, int id, Account acct) { this.name = name; this.age = age; this.id = id; this.acct = acct; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", id=" + id + ", acct=" + acct + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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 Person(String name, int age) { this.name = name; this.age = age; } public Person() { } } class Account implements Serializable{ public static final long serialVersionUID = 4754534532L; private double balance; @Override public String toString() { return "Account{" + "balance=" + balance + '}'; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public Account(double balance) { this.balance = balance; } }
2.6 byte stream write out
2.6.1 OutputStream Abstract parent class
Note: this abstract class is a super class representing all classes of output byte stream, and the construction method is not studied.
Common methods:
void close() Close this output stream and free all system resources associated with this stream. void flush() Refresh this output stream and force all buffered output bytes to be written out. void write(byte[] b) take b.length Bytes from the specified byte Array writes to this output stream. void write(byte[] b, int off, int len) Will specify byte Offset from array off Started len Bytes are written to this output stream. abstract void write(int b) Writes the specified byte to this output stream. ......
2.6.2 FileOutputStream subclass (node stream: File byte stream)
Note: insert it directly into the file and write out the file data directly
Create object:
1. FileOutputStream(File file) Create a specified File Object to write data to the file output stream. 2. FileOutputStream(File file, boolean append) Create a specified File Object to write data to the file output stream. 3. FileOutputStream(FileDescriptor fdObj) Creates an output file stream that writes data to a specified file descriptor that represents an existing connection to an actual file in the file system. 4. FileOutputStream(String name) Creates an output file stream that writes data to a file with the specified name. 5. FileOutputStream(String name, boolean append) Create a file with the specified name The output file stream in which data is written.
Test:
package com.io_file; import org.junit.Test; import java.io.*; /** * Test the use of FileInputStream and FileOutputStream * * Conclusion: * 1. For text files (. txt,.java,.c,.cpp), use character stream processing (because byte stream processing Chinese is garbled) * Note that the garbled code here refers to the garbled code when the data is viewed at the memory level. If it is simply copied from the hard disk -- > hard disk, the text file can still be processed by byte stream. * 2. For non text files (. jpg,.mp3,.mp4,.avi,.doc,.ppt,...), Only byte stream processing can be used (because the basic unit of these non text files is relatively small, and the unit of characters is relatively large, which can not be processed) * * * * @author shkstart * @create 2019 2:13 PM */ public class FileInputOutputStreamTest { /* Copy the picture */ @Test public void testFileInputOutputStream() { FileInputStream fis = null; FileOutputStream fos = null; try { // File srcFile = new File("Love and friendship.jpg"); File destFile = new File("Love and friendship 2.jpg"); // fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //Replication process byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) != -1){ fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fos != null){ // try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Encapsulated into the writing method of tool Api: copy files (video, pictures, audio, etc.) (text) under the specified path. Simple copy can be used regardless of any type of file and byte stream. public void copyFile(String srcPath,String destPath){ FileInputStream fis = null; FileOutputStream fos = null; try { // File srcFile = new File(srcPath); File destFile = new File(destPath); // fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //Replication process byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) != -1){ fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fos != null){ // try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void testCopyFile(){ long start = System.currentTimeMillis(); String srcPath = "D:\\aa\\bb\\01-Shang Silicon Valley-Java Language foundation.avi"; String destPath = "D:\\aa\\bb\\02-Shang Silicon Valley-Java Language foundation.avi"; // String srcPath = "hello.txt"; // String destPath = "hello3.txt"; copyFile(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("The time taken for the copy operation is:" + (end - start));//618 } }
2.6.3 BufferedOutputStream subclass (processing stream: buffered byte stream)
Description: this class implements buffered output stream. By setting this output stream, the application can write each byte to the underlying output stream without calling the underlying system for each byte write.
Create object:
1. BufferedOutputStream(OutputStream out) Create a new buffered output stream to write data to the specified underlying output stream. 2. BufferedOutputStream(OutputStream out, int size) Create a new buffered output stream to write data with the specified buffer size to the specified underlying output stream.
Test: check the test in 2.5.3.
2.6.4 ObjectOutputStream subclass (processing stream: object output stream / serialization)
Omitted, see 2.5.4 for details
2.7 byte stream after class exercise
2.7.1 encryption and decryption of pictures
package com.io_file; import org.junit.Test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * @author shkstart * @create 2019 4:08 PM */ public class PicTest { //Image encryption: after the original image is encrypted and copied, because the XOR operation disturbs the order, the image size is the same but cannot be opened. @Test public void test1() { FileInputStream fis = null; FileOutputStream fos = null; try { /* fis = new FileInputStream("Love and friendship jpg "); equivalent to fis = new FileInputStream(new File(" love and friendship. jpg "); * FileInputStream This constructor that can directly write the path, in fact, the path inside is wrapped in new File(). * * */ fis = new FileInputStream("Love and friendship.jpg");//Real existence fos = new FileOutputStream("Love and friendship secret.jpg");//The encrypted image will be automatically generated: because the XOR operation disturbs the order, the image size is the same but cannot be opened. byte[] buffer = new byte[20]; int len; while ((len = fis.read(buffer)) != -1) { //Modify byte array //The wrong enhanced for loop is to assign buffer to a new variable, and the value in the array has not changed. // for(byte b : buffer){ // b = (byte) (b ^ 5); //b ^ 5: XOR operation, disrupting the bytes inside. // } //correct for (int i = 0; i < len; i++) { buffer[i] = (byte) (buffer[i] ^ 5); //buffer is byte type and 5-bit int type. The calculation result is consistent with the large type, so it needs to be forced. } fos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Image decryption: Principle: XOR operation, m^n^n=m @Test public void test2() { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("Love and friendship secret.jpg"); fos = new FileOutputStream("Love and friendship 4.jpg"); byte[] buffer = new byte[20]; int len; while ((len = fis.read(buffer)) != -1) { //Modify byte array //FALSE // for(byte b : buffer){ // b = (byte) (b ^ 5); // } //correct for (int i = 0; i < len; i++) { buffer[i] = (byte) (buffer[i] ^ 5); } fos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
2.7.2 obtain the number of characters on the text and write the data into the file
package com.io_file; import org.junit.Test; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Get the number of characters on the text and write the data to the file * * Idea: * 1.Traverse each character of the text * 2.The number of times characters appear exists in the Map * * Map<Character,Integer> map = new HashMap<Character,Integer>(); * map.put('a',18); * map.put('You ', 2); * * 3.Write the data in the map to the file * * @author shkstart * @create 2019 3:47 PM */ public class WordCount { /* Note: if unit testing is used, the relative path of the file is the current module If the main() test is used, the relative path of the file is the current project */ @Test public void testWordCount() { FileReader fr = null; BufferedWriter bw = null; try { //1. Create a Map set k: store characters v: store times Map<Character, Integer> map = new HashMap<Character, Integer>(); //2. Traverse each character and put the number of occurrences of each character into the map fr = new FileReader("dbcp.txt"); int c = 0; while ((c = fr.read()) != -1) { //int restore char char ch = (char) c; // Determine whether char appears for the first time in the map if (map.get(ch) == null) { map.put(ch, 1); } else { map.put(ch, map.get(ch) + 1);//The value is increased by 1 in the original times } } //3. Save the data in the map to the file count Txt, because it is not safe to put it in memory. //3.1 create Writer bw = new BufferedWriter(new FileWriter("wordcount.txt")); //3.2 traverse the map and then write the data Set<Map.Entry<Character, Integer>> entrySet = map.entrySet(); for (Map.Entry<Character, Integer> entry : entrySet) { switch (entry.getKey()) { case ' ': bw.write("Space=" + entry.getValue()); break; case '\t'://\t represents the tab key character bw.write("tab key=" + entry.getValue()); break; case '\r':// bw.write("enter=" + entry.getValue()); break; case '\n':// bw.write("Line feed=" + entry.getValue()); break; default: bw.write(entry.getKey() + "=" + entry.getValue()); break; } bw.newLine();//Wrap after writing } } catch (IOException e) { e.printStackTrace(); } finally { //4. Shut down if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
3 IO stream – 02
3.1 character stream reading
Description: it is often used to process plain text data.
3.1.1 Reader Abstract parent class
Note: the abstract parent class used to read the character stream cannot be a new object since it is an abstract class, so we only study the common methods, not the construction methods.
Common methods:
int read() Read a single character. It is inefficient to read one character at a time. int read(char[] cbuf) Note that char Read characters into an array. abstract int read(char[] cbuf, int off, int len) Read characters into a part of the array. five,3 The length of the array is 5, but a maximum of 3 are read in each time. int read(CharBuffer target) An attempt was made to read a character into the specified character buffer. abstract void close() Close the flow and release all resources associated with it. ......
3.1.2 FileReader subclass (node stream: file character stream)
Description: a convenient class for reading character files.
Construction method:
1. FileReader(String fileName) //The parameter is the path of the file Creates a new file given the name of the file from which the data is read FileReader. 2. FileReader(File file) Read data from a given File Create a new case FileReader. 3. FileReader(FileDescriptor fd) Read data from a given FileDescriptor Create a new FileReader.
Common methods: no special methods are generated, which are all from inheritance and Java lang.Object,java.io.Reader,java. io. Method of inputstreamreader class.
Test:
package com.io_file; import org.junit.Test; import java.io.*; /** * * 1, Classification of flow: * 1.Operation data unit: byte stream, character stream * 2.Data flow direction: input flow and output flow * 3.Roles of flow: node flow and processing flow * * 2, Flow architecture * Abstract base class node stream (or file stream) buffer stream (a kind of processing stream) * InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer)) * OutputStream FileOutputStream (write(byte[] buffer,0,len) BufferedOutputStream (write(byte[] buffer,0,len) / flush() * Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine()) * Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / flush() * * * * @author shkstart * @create 2019 10:40 am */ public class FileReaderWriterTest { public static void main(String[] args) { File file = new File("hello.txt");//The relative path uses the main method, which is compared with the current project System.out.println(file.getAbsolutePath());//E:\idea-workspace\hello.txt File file1 = new File("day09\\hello.txt");//The relative path uses the main method, starting from the current module System.out.println(file1.getAbsolutePath());//E:\idea-workspace\day09\hello.txt } /* Put hello. Under the io project in idea Txt file content is read into the program and output to the console Description: 1. read()Return a character read in. If the end of the file is reached, - 1 is returned 2. Exception handling: to ensure that flow resources can be closed. Try catch finally processing is required. If you use throws to handle exceptions, once an exception occurs in the program After throwing the exception, the subsequent code will not be executed. If an exception occurs in the second occurrence, then the next code close will not be executed, and the waste of resources is obviously inappropriate. 3. The read file must exist, otherwise FileNotFoundException will be reported. */ @Test public void testFileReader(){ FileReader fr = null; try { //1. Instantiate the object of File class to indicate the File to be operated File file = new File("hello.txt");//Compared to the current Module //2. Provide specific flow fr = new FileReader(file);//Place 1 where exceptions occur: exceptions will be thrown when creating objects //3. Data reading //read(): returns a character read in. If the end of the file is reached, it is inefficient to return - 1 and read one character at a time. //Mode 1: // int data = fr.read();// The character is of char type, and the int type is used here because the corresponding code 97 Data stored in this way. // while(data != -1){ // System.out.print((char)data);// Read the first one. If it is not - 1, read it, and convert it to char type character reception. Otherwise, the output is a number. Output does not wrap // data = fr.read();// Start reading the second one and assign the value to the data loop to judge whether the second one is - 1 // } //Mode 2: grammatical modification of mode 1 int data; while((data = fr.read()) != -1){//Exception 2: the read method returns an exception System.out.print((char)data); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Close flow: there is nothing you can do about physical connections, such as database connection, input / output flow and Socket connection. These resources need to be closed manually. // try { // If (fr! = null) / / because fr is written outside and declared null, if the object is not created successfully after the first exception, null pointer exception will appear in finally, so judge if. // fr.close();// Place 3 where exceptions occur: close returns exceptions, and the closed resources are usually in finally, so a separate try catch is used instead of finally. // } catch (IOException e) { // e.printStackTrace(); // } //or if(fr != null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Upgrade the read() operation: use the overloaded method of read @Test public void testFileReader1() { FileReader fr = null; try { //1. Instantiation of file class File file = new File("hello.txt"); //2. Instantiation of FileReader stream fr = new FileReader(file); //3. Read in operation //read(char[] cbuf): returns the number of characters read into the cbuf array each time. If the end of the file is reached, - 1 is returned char[] cbuf = new char[5];//Read the specified number of characters each time, 5 characters int len; while((len = fr.read(cbuf)) != -1){//Read 5 data into hellow5 files each time. //Mode 1: //Wrong writing // for(int i = 0;i < cbuf.length;i++){ // System.out.print(cbuf[i]);helloworld123ld because the array is an overlay operation, the first time [h,e,l,l,o], the second time [w,o,r,l,d], the third time [1,2,3,l,d] //Each time the newly read data overwrites the original array value, there are only three data at the last time. Traverse the output array and output the other two data. // } //Correct writing // For (int i = 0; I < len; I + +) {/ / each time you read in a few, you can traverse a few // System.out.print(cbuf[i]); // } //Mode 2: //The wrong way of writing, corresponding to the wrong way of writing in mode 1, remains ld // String str = new String(cbuf);//char to string type // System.out.print(str); //Correct writing String str = new String(cbuf,0,len);//Take values from the beginning, only len at a time System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if(fr != null){ //4. Closure of resources try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
3.1.3 BufferedReader subclass (processing stream: buffered character stream)
Description: read the text from the character input stream and buffer each character, so as to realize the efficient reading of characters, arrays and lines. You can specify the size of the buffer, or you can use the default size. In most cases, the default value is large enough.
Create object:
1. BufferedReader(Reader in) Create a buffered character input stream that uses the default size input buffer. 2. BufferedReader(Reader in, int sz) Creates a buffered character input stream using an input buffer of the specified size.
Test:
package com.bf_file; import org.junit.Test; import java.io.*; /** * One of the processing streams: the use of buffer streams * * 1.Buffer stream: * BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter * * 2.Function: provide the read and write speed of the stream * The reason for improving the reading and writing speed: a buffer is provided internally (a certain amount of data is read into the buffer and written out at one time) * * 3. Processing flow is "socket connection". Based on the existing flow, the processing flow cannot directly act on the file. * * @author shkstart * @create 2019 2:44 PM */ public class BufferedTest { /* Use BufferedReader and BufferedWriter to copy text files */ @Test public void testBufferedReaderBufferedWriter(){ BufferedReader br = null; BufferedWriter bw = null; try { //Create files and corresponding streams br = new BufferedReader(new FileReader(new File("dbcp.txt"))); bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt"))); //Read / write operation //Method 1: use char [] array // char[] cbuf = new char[1024]; // int len; // while((len = br.read(cbuf)) != -1){ // bw.write(cbuf,0,len); // // bw.flush(); // } //Method 2: use string readline() to read one line at a time. When it is null, it means there is no data behind it. String data; while((data = br.readLine()) != null){ //bw.write(data); //data does not contain newline characters. By default, it does not contain newline characters, and they are written in one line. //Add line feed to method 1: // bw.write(data + "\n"); //Add line break to method 2: bw.write(data);//data does not contain line breaks bw.newLine();//Provides line feed operations } } catch (IOException e) { e.printStackTrace(); } finally { //close resource if(bw != null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
3.1.4 InputStreamReader subclass (processing flow: conversion flow)
explain:
- Used as a bridge to transfer bytes into character stream.
- Used to solve the problem of character stream reading and writing garbled code.
Construction method:
1. InputStreamReader(InputStream in) Create a character that uses the default character set InputStreamReader. 2. InputStreamReader(InputStream in, Charset cs) Create a with the given character set InputStreamReader. 3. InputStreamReader(InputStream in, CharsetDecoder dec) Create a decoder that uses the given character set InputStreamReader. 4. InputStreamReader(InputStream in, String charsetName) Creates a with the specified character set InputStreamReader.
Common methods:
void close() Close the flow and release all resources associated with it. String getEncoding() Returns the name of the character encoding used by this stream. int read() Read a single character. int read(char[] cbuf, int offset, int length) Reads characters into a part of an array. boolean ready() Determine whether the stream is ready for reading.
Test:
package com.io_file; import org.junit.Test; import java.io.*; /** * Processing flow 2: use of conversion flow * 1.Conversion stream: belongs to character stream * InputStreamReader: Converts a byte input stream to a character input stream * OutputStreamWriter: Converts the output stream of one character to the output stream of bytes * * 2.Function: provide conversion between byte stream and character stream * * 3. Decoding: byte, byte array -- > character array, string (can't understand -- > can understand) * Encoding: character array, string -- > byte, byte array (understand -- > can't understand) * * * 4.character set *ASCII: American standard information interchange code. It can be represented by 7 bits of a byte. ISO8859-1: Latin code table. European code table Represented by 8 bits of a byte. GB2312: Chinese coding table of China. Up to two bytes encode all characters GBK: China's Chinese coding table has been upgraded to integrate more Chinese characters and symbols. Up to two byte encoding Unicode: International standard code, which integrates all characters currently used by human beings. Assign a unique character code to each character. All text is represented by two bytes. UTF-8: Variable length encoding method, which can represent a character with 1-4 bytes. * * * @author shkstart * @create 2019 4:25 PM */ public class InputStreamReaderTest { /* Read the specified file into memory and output it to the console: At this time, try catch finally should still be used to handle exceptions. Here, it is lazy and uses throws. InputStreamReader To realize the conversion from byte input stream to character input stream */ @Test public void test1() throws IOException { FileInputStream fis = new FileInputStream("dbcp.txt"); // InputStreamReader isr = new InputStreamReader(fis);// Use the system's default character set and keep consistent with the encoding set in your idea. //Parameter 2 indicates the character set. The specific character set depends on the file DBCP Txt character set used when saving (i.e. the code when reading should be consistent with the code set in the read file) InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//Use the specified character set and keep consistent with the read file character set encoding. char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ String str = new String(cbuf,0,len); System.out.print(str); } isr.close(); } /* At this time, try catch finally should still be used to handle exceptions. Here, it is lazy and uses throws. Use InputStreamReader and OutputStreamWriter together Procedure: utf8 in hard disk Txt -- > file byte stream -- > byte input stream -- > character input conversion stream (UTF-8, consistent with the encoding of the saved file) - -- > memory --->Character output conversion stream (GBK, select the character you want to encode) - > byte output stream -- > file output stream --- GBK in hard disk Txt file */ @Test public void test2() throws Exception { //1. Document making and flow making File file1 = new File("dbcp.txt"); File file2 = new File("dbcp_gbk.txt");//If you want to view it, you can only use gbk to view it, which is not random code. FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); InputStreamReader isr = new InputStreamReader(fis,"utf-8"); OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk"); //2. Reading and writing process char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ osw.write(cbuf,0,len); } //3. Close resources isr.close(); osw.close(); } }
3.1.5 common character coding table
Origin of coding table: computers can only recognize binary data, and the early origin was electrical signals. In order to facilitate the application of the computer, it can recognize the characters of various countries. The words of each country are expressed in numbers and correspond one by one to form a table. This is the coding table.
Garbled code refers to Chinese garbled Code:
- How did it happen? It is because the code table you use when saving is inconsistent with the code table you use when opening.
- Solution: just save and open the unified code table.
code | brief introduction | explain | Coding range | Byte quantity |
---|---|---|---|---|
ASCII | American Standard Information Interchange Code | English, punctuation, basic instructions | 0 to 127 | It can be represented by 7 bits of a byte. (single byte) |
ISO8859-1 | Latin code table | It is compatible with ASCII and extends Western European characters on this basis | 128 to 255 | Represented by 8 bits of a byte. (single byte) |
GB2312 | Chinese coding table of China | ASCII compatible | Up to two bytes encode all characters | |
GBK | Upgrade of Chinese coding table in China | It is compatible with ASCII and integrates more Chinese characters and symbols | 65535 Max | Up to two bytes encode all characters. (single byte for English and double byte for Chinese) |
Unicode | International Standard Code | International standard code, which integrates all characters currently used by human beings. Assign a unique character code to each character, which is ASCII compatible. | 1 million + coding bits, divided into common character table, rare character table, etc. we just use common table | All text is represented by two bytes. (all characters in the common character table adopt double bytes) |
UTF-8 | Optimized international standard code | In order to solve the problem of doubling the number of bytes of Unicode English characters, a variable length encoding format is proposed, which is compatible with ASCII. | A character can be represented by 1-4 bytes. (English single byte, some characters double byte, Chinese three bytes, some special symbols four bytes) |
Unicode encoding problem:
matters needing attention:
-
ANSI code usually refers to the default code of the platform. For example, ISO-8859-1 in English operating system and GBK in Chinese system.
-
Unicode character set only defines the set and unique number of characters. Unicode coding is a general term for specific coding schemes such as UTF-8 and UCS-2/UTF-16
It is not a specific coding scheme.
Enlightenment for later learning:
- Client / browser < --------- > background (Java, go, python, nod.js, PHP) < --------- > Database
- It is required that the character set used before and after should be unified: UTF-8.
3.2 character stream writing
3.2.1 Writer Abstract parent class
Description: the abstract class written to the character stream also does not study the construction method.
Common methods:
void write(char[] cbuf) Write character array. char abstract void write(char[] cbuf, int off, int len) Writes a part of a character array. void write(int c) Write a single character. void write(String str) Write string. void write(String str, int off, int len) Write a part of a string. abstract void close() Close this stream, but refresh it first. ......
3.2.2 FileWriter subclass (node stream: file character stream)
Description: a convenient class for writing character files.
Create object:
1. FileWriter(File file) According to the given File Object to construct a FileWriter Object. 2. FileWriter(File file, boolean append) According to the given File Object to construct a FileWriter Object. 3. FileWriter(FileDescriptor fd) Construct a file associated with a file descriptor FileWriter Object. 4. FileWriter(String fileName) Construct a file based on the given file name FileWriter Object. 5. FileWriter(String fileName, boolean append) Based on the given file name and the information indicating whether to attach the written data boolean Value to construct FileWriter Object.
Common methods: no special methods are generated, which are all from inheritance and Java lang.Object,java.io.Writer,java. io. Method of the outputstreamwriter class.
Test:
package com.io_file; import org.junit.Test; import java.io.*; /** * * 1, Classification of flow: * 1.Operation data unit: byte stream, character stream * 2.Data flow direction: input flow and output flow * 3.Roles of flow: node flow and processing flow * * 2, Flow architecture * Abstract base class node stream (or file stream) buffer stream (a kind of processing stream) * InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer)) * OutputStream FileOutputStream (write(byte[] buffer,0,len) BufferedOutputStream (write(byte[] buffer,0,len) / flush() * Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine()) * Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / flush() * * * * @author shkstart * @create 2019 10:40 am */ public class FileReaderWriterTest { /* Write data from memory to a file on the hard disk. explain: 1. For output operation, the corresponding File may not exist. No exception will be reported 2. File If the file in the corresponding hard disk does not exist, it will be automatically created during the output process. File If the file in the corresponding hard disk exists: If the constructor used by the stream is: FileWriter(file,false) / FileWriter(file): overwrite the original file If the constructor used by the stream is: FileWriter(file,true): it will not overwrite the original file, but add content on the basis of the original file */ @Test public void testFileWriter() {//To write code, you can throw an exception first, and then change it to try catch after writing the code, so that the code is easier to understand. FileWriter fw = null; try { //1. Provide the object of File class to indicate the File to be written out File file = new File("hello1.txt"); //2. Provide the object of FileWriter for writing out data fw = new FileWriter(file,false); //3. Write out the operation fw.write("I have a dream!\n"); fw.write("you need to have a dream!"); } catch (IOException e) { e.printStackTrace(); } finally { //4. Closing of flow resources if(fw != null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Put the hard disk hello Txt data is read into the memory, and the data in the memory is written out to the hard disk hello2 Txt. @Test public void testFileReaderFileWriter() { FileReader fr = null; FileWriter fw = null; try { //1. Create an object of File class to indicate the files read in and written out File srcFile = new File("hello.txt"); File destFile = new File("hello2.txt"); //Character streams cannot be used to process byte data such as pictures // File srcFile = new File("love and friendship. jpg"); // File destFile = new File("love and friendship 1.jpg"); //2. Create objects for input and output streams fr = new FileReader(srcFile); fw = new FileWriter(destFile); //3. Data reading and writing char[] cbuf = new char[5]; int len;//Record the number of characters read into the cbuf array each time while((len = fr.read(cbuf)) != -1){ //Write len characters at a time, read a few characters at a time, and write a few characters at a time fw.write(cbuf,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Close stream resources. There is no requirement for the resource closing sequence of the two streams. //Mode 1: // try { // if(fw != null) // fw.close(); // } catch (IOException e) { // e.printStackTrace(); // }finally{ // try { // if(fr != null) // fr.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } //Mode 2: try { if(fw != null) fw.close(); } catch (IOException e) { e.printStackTrace(); } try { if(fr != null) fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
3.2.3 BufferedWriter subclass (processing stream: buffer stream)
Description: write text to the character output stream and buffer each character, so as to provide efficient writing of single character, array and string. You can specify the size of the buffer or accept the default size. In most cases, the default value is large enough.
Create object:
1. BufferedWriter(Writer out) Create a buffered character output stream that uses the default size output buffer. 2. BufferedWriter(Writer out, int sz) Creates a new buffered character output stream using an output buffer of a given size.
Test: see 3.1.3 for details
3.2.4 OutputStreamWriter subclass (processing flow: conversion flow)
explain:
- Used as a bridge to transfer characters into byte stream.
- Used to solve the problem of garbled code written in character stream.
Construction method:
1. OutputStreamWriter(OutputStream out) Create a with default character encoding OutputStreamWriter. 2. OutputStreamWriter(OutputStream out, Charset cs) Create a with the given character set OutputStreamWriter. 3. OutputStreamWriter(OutputStream out, CharsetEncoder enc) Creates an encoder that uses the given character set OutputStreamWriter. 4. OutputStreamWriter(OutputStream out, String charsetName) Creates a with the specified character set OutputStreamWriter.
Common methods:
void close() Close this stream, but refresh it first. void flush() Flush the buffer of the stream. String getEncoding() Returns the name of the character encoding used by this stream. void write(char[] cbuf, int off, int len) Writes a part of a character array. void write(int c) Write a single character. void write(String str, int off, int len) Write a part of a string.
Test: see 3.1.4 for details
3.3 use of other streams (not commonly used)
3.3.1 standard input and output streams (System.in, System.out)
Null pointer before and after equals parameter???
explain:
- System.in and system Out represents the input and output devices of the system standard respectively
- The default input device is keyboard, and the output device is display
- System. The type of in is InputStream
- System. The type of out is PrintStream, which is a subclass of OutputStream and a subclass of FilterOutputStream
- Redirection: change the default device through the setIn and setOut methods of the System class. (for example, the data printed to the console will be printed to the file. See the print stream for details)
The public static void setIn(InputStream in) parameter is the InputStream byte input stream
The stream print parameter is setvoid stream (public stream print)
Inheritance relationship:
Note: input characters (Scanner input, standard input stream and output stream System.in System.out) on the console with the keyboard, and the data may not be input.
- If it is written in idea, the main method can input data on the console, but the test method can not input data on the console.
- In eclipse, you can enter data whether it is written in the main method or the test method.
practice:
package com.io_file; import org.junit.Test; import java.io.*; /** * Use of other streams * 1.Standard input and output streams * 2.Print stream * 3.data stream * * @author shkstart * @create 2019 6:11 PM */ public class OtherStreamTest { /* 1.Standard input and output streams 1.1 System.in:Standard input stream, input from keyboard by default System.out:The standard output stream is output from the console by default 1.2 System The setIn(InputStream is) / setOut(PrintStream ps) method of class re specifies the input and output streams. 1.3 practice: When inputting a string from the keyboard, it is required to convert the read whole line of string into uppercase output. Then continue the input operation, Until you enter "e" or "exit", exit the program. Method 1: use the Scanner implementation and call next() to return a string Method 2: use system In implementation. System.in (the return value is of InputStream type, the byte stream needs to be converted into character stream in the middle) - > conversion stream -- > readLine() of BufferedReader) */ public static void main(String[] args) { BufferedReader br = null; try { InputStreamReader isr = new InputStreamReader(System.in); br = new BufferedReader(isr); while (true) { System.out.println("Please enter a string:"); String data = br.readLine();//Read one line of data at a time /* * equalsIgnoreCase() : Ignore case for equality comparison * equals(): Case equality is not ignored. * * It is impossible for the pointer to be null in this way * if (data.equalsIgnoreCase("e") || data.equalsIgnoreCase("exit")){ * * } * */ if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {//It can better avoid the occurrence of null pointers System.out.println("Program end"); break; } String upperCase = data.toUpperCase();//Convert to uppercase System.out.println(upperCase); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
3.3.2 print stream (Advanced stream: PrintStream and PrintWriter)
explain:
- The data format of basic data types is converted into string output, and various types of data can be output.
- Print streams: PrintStream and PrintWriter
- Provides a series of overloaded print() and println() methods for output of multiple data types
- The output of PrintStream and PrintWriter will not throw IOException
- PrintStream and PrintWriter have automatic flush function
- All characters printed by PrintStream are converted to bytes using the platform's default character encoding.
When you need to write characters instead of bytes, you should use the PrintWriter class. - System.out returns an instance of PrintStream
Inheritance relationship:
- Byte printout stream
- Character printout stream
Test:
package com.io_file; import org.junit.Test; import java.io.*; /** * Use of other streams * 1.Standard input and output streams * 2.Print stream * 3.data stream * * @author shkstart * @create 2019 6:11 PM */ public class OtherStreamTest { /* 2. Print stream: PrintStream and PrintWriter can output various types of data. 2.1 Provides a series of overloaded print() and println() 2.2 Exercise: output ASCII characters (decimal) corresponding to 0-255 numbers to the corresponding file What needs to be used: print the output data to the console instead of to the file. */ @Test public void test2() { PrintStream ps = null; try { //Note this file path: at the beginning, the file directory (the lowercase IO directory written on the disk, the uppercase IO directory written here, and the directory is not case sensitive in windows) needs to exist. If the file (text.txt) does not exist, it will help you create it automatically. FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt")); // Create a printout stream and set it to automatic refresh mode (the output buffer will be refreshed when writing newline character or byte '\ n') ps = new PrintStream(fos, true);//true stands for automatic flush operation if (ps != null) { System.setOut(ps);// Change standard output stream (console output) to file setOut(): reassign a print stream object ps } for (int i = 0; i <= 255; i++) { // Output ASCII characters: a -- > 97 (decimal) a -- > 65 (decimal) 0 -- > 48 (decimal) System.out.print((char) i); if (i % 50 == 0) { // One row for every 50 data System.out.println(); // Line feed } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } } } }
3.3.3 data flow (advanced flow: DataInputStream and DataOutputStream)
explain:
Inheritance relationship:
- Data input stream
- Data output stream
Test:
package com.io_file; import org.junit.Test; import java.io.*; /** * Use of other streams * 1.Standard input and output streams * 2.Print stream * 3.data stream * * @author shkstart * @create 2019 6:11 PM */ public class OtherStreamTest { /* 3. data stream 3.1 DataInputStream And DataOutputStream 3.2 Function: used to read or write variables or strings of basic data types Exercise: write out strings in memory and variables of basic data types into files. However, you cannot read or write objects. To read or write objects, you need to use object input stream and object output stream (deserialization, serialization). Note: try catch finally should still be used to handle exceptions */ //Write before read: first write the data in memory to a file. This file is binary data and cannot be opened for reading directly. If you want to read, you can only read the data into memory and output it to the console for viewing @Test public void test3() throws IOException { //1. DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")); //2. dos.writeUTF("Liu Jianchen"); dos.flush();//Refresh operation: write the data in memory to the file (once the refresh operation is performed, the existing data in memory will be refreshed to the file) dos.writeInt(23); dos.flush(); dos.writeBoolean(true); dos.flush(); //3. dos.close(); } /* Read the basic data type variables and strings stored in the file into memory and save them in variables. Note: the order of reading different types of data should be consistent with the order of saved data when writing the file! */ @Test public void test4() throws IOException { //1. DataInputStream dis = new DataInputStream(new FileInputStream("data.txt")); //2. String name = dis.readUTF(); int age = dis.readInt(); boolean isMale = dis.readBoolean(); System.out.println("name = " + name); System.out.println("age = " + age); System.out.println("isMale = " + isMale); //3. dis.close(); } }
3.3.4 random access file
summary:
Inheritance structure:
Construction method:
Parameter 1: file name Parameter 2: see test code for details 1.RandomAccessFile(File file, String mode) Creates a random access file stream from which to read and (optionally) write to, which is created by File Parameter assignment. Parameter 1: Path Parameter 2 2.RandomAccessFile(String name, String mode) Creates a random access file stream from which to read and (optionally) write to, with the specified name.
Test:
package Random_File; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; /** * RandomAccessFile Use of * 1.RandomAccessFile Directly inherited from Java Lang. object class, which implements DataInput and DataOutput interfaces * 2.RandomAccessFile It can be used as both an input stream and an output stream. However, you still need two objects to create, one for reading and one for writing * * 3.If RandomAccessFile is used as the output stream, if the file written out does not exist, it will be automatically created during execution. * If the file written out exists, the contents of the original file will be overwritten. (by default, overwrite from scratch) * * 4. The RandomAccessFile can "insert" data through relevant operations * * @author shkstart * @create 2019 11:18 am */ public class RandomAccessFileTest { //Copy of test picture @Test public void test1() { RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try { //1. /* Value of parameter 2mode: * r: Open write in read-only mode. r can only read, not write * rw: Open for reading and writing * rwd:Open for reading and writing; Synchronize file content updates * rws:Open for reading and writing; Synchronize file content and metadata updates * * matters needing attention: * If the mode is read-only r. Instead of creating a file, it will read an existing file. If the read file does not exist, an exception will appear. (it can only be used for reading, and will not be created if the file does not exist during reading) * If the mode is rw read / write. If the file does not exist, it will be created. If it does exist, it will not be created. (if the file does not exist, both read and write will create a file, but there is nothing in the file. If the file is written * (if it exists, it will be overwritten) * * */ raf1 = new RandomAccessFile(new File("Love and friendship aa.jpg"),"rw");//As input raf2 = new RandomAccessFile(new File("Love and friendship aa1.jpg"),"rw");//As output //2. byte[] buffer = new byte[1024]; int len; while((len = raf1.read(buffer)) != -1){ raf2.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //3. if(raf1 != null){ try { raf1.close(); } catch (IOException e) { e.printStackTrace(); } } if(raf2 != null){ try { raf2.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Test the coverage effect: create the file hello Txt, write out the content to this file to see if it is overwritten. /*Note that the entire file is not overwritten, but the contents are overwritten from the beginning (the pointer is 0). * For example, the original file hello txt: hello123bbb * If the written data is xyz, the file content becomes xyzlo123bbb * This pointer can be adjusted, such as raf1 Seek (3) adjust the pointer to the position with the corner mark of 3, that is, overwrite from the corner mark of 3 (the fourth data) * For example, the original file hello txt: hello123bbb * If the written data is xyz, the file content becomes: helxyz23bbb * * Think about how to append data after hello123bbb: * You need to specify the pointer to the end of the File: a method length() is provided in the File class to obtain the length of the File * For example, if the length of hello123bbb is 11, the subscript starts from 0, and the last b is 10, then the subscript 11 at the end is exactly the length of the file. */ @Test public void test2() throws IOException { RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw"); raf1.seek(3);//Adjust the pointer to the position marked with angle 3 raf1.write("xyz".getBytes());//getBytes(): encodes this String into a byte sequence using the specified character set, and stores the result in a new byte array. raf1.close(); } /* * RandomAccessFile is used to realize the data insertion effect: it can only be overwritten, so how to realize the insertion effect??? * For example, the original file hello txt: hello123bbb * Now you want to insert ccc after 123 * Idea: first adjust the pointer to the position of b and take out the bbb. When copying, the pointer will also move backward. At this time, the pointer is in the last position, * Then adjust the pointer to the back of 3, add ccc, and splice the copied data to the back. hello123cccbbb * */ @Test public void test3() throws IOException { RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw"); raf1.seek(8);//Adjust the pointer to the position marked with angle 3 //Save all the data behind pointer 3 to the specified length in StringBuilder to create a String StringBuilder builder = new StringBuilder((int) new File("hello.txt").length()); byte[] buffer = new byte[20]; int len; while((len = raf1.read(buffer)) != -1){ //The parameters of the append method cannot be directly passed to an array of byte type, but can be passed to a String type, which can be passed to an array of char type builder.append(new String(buffer,0,len)) ;//If the array has no data, it is added to the array (abc+dd=abcdd,null+dd=dd) } //Call back the pointer and write "xyz" raf1.seek(8); raf1.write("ccc".getBytes());//The pointer is at the end of the file //Write data from StringBuilder to file raf1.write(builder.toString().getBytes());//The write parameter is bytes. StringBuilder does not provide getBytes() method. First convert it to String type and call getBytes() method. raf1.close(); //Think: replace StringBuilder with ByteArrayOutputStream day617 } }
3.4 NIO introduction
3.4.1 introduction to common sense
-
Blocking IO, BIO is the traditional Java IO package is implemented based on the flow model. The interaction mode is synchronous and blocking, that is, when reading in the input stream or output stream, the thread will be blocked there until the reading and writing action is completed, and the calls between them are in a reliable linear order. Its advantage is that the code is relatively simple and intuitive; The disadvantage is the low efficiency and scalability of IO, which is easy to become the bottleneck of application performance.
-
Non blocking IO, NIO is a java.0 introduced by Java 1.4 NIO package provides new abstractions such as Channel, Selector and Buffer, which can build multiplexed, synchronous and non blocking IO programs, and provide a high-performance data operation mode closer to the bottom of the operating system.
-
Asynchronous IO, AIO is a package introduced after Java 1.7 and an upgraded version of NIO. It provides asynchronous and non blocking IO operation mode, so people call it AIO (asynchronous IO). Asynchronous IO is implemented based on event and callback mechanism, that is, it will return directly after application operation and will not be blocked there. When the background processing is completed, The operating system will notify the corresponding thread to carry out subsequent operations. But at present, it is not mature enough and has few applications.
3.4.2 NIO overview
3.5 import the jar package of the third party to realize reading and writing
3.5.1 general
explain:
- The code of the real io stream in development may be written by yourself, or it may directly call the Api of the jar package. Its underlying source code or encapsulates these io operations, which makes the call easier.
- Before learning spring boot, you need to add jar package manually to use ar package.
3.5.2 add jar package test
Take idea as an example to add a jar package:
- Copy the jar package.
- The directory created in the idea project is generally libs
- Copy the jar package to this directory
- Put the jar package into effect:
3.5.3 code writing test
3.6 expansion
3.6.1 difference between flush() and close() in io
- Flush() refreshes the data to the destination, and the stream can continue to be used.
- Close() closes the stream. Before closing, the data will be refreshed to the destination. After closing, the stream cannot continue to be used.