clone
protected Object clone() Creates and returns a copy of this object. protected Object clone() throws CloneNotSupportedException
All classes inherit Object, so all classes have clone() methods. But not all classes want to be cloned. They must support the clonable interface. This interface doesn't have any methods, it just describes a capability.
Date
Easy to use:
long getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
Returns the millisecond level time, starting from 1970-1-1; that is, the millisecond of a long returned, from 1970 to now, how many millimeters;
new Data() view the current time, but the format is not standard;
At this point, you can borrow the SimpleDateFormat class
Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String str = sdf.format(date); System.out.println(str);
regular
1. Character matching [quantity: single]
- Arbitrary character
- '\ \': match '\';
- '\ n': match newline
- \t: match table character;
2. Character set matching [quantity: single]
- [abc] may be any one of abc
- [^ abc] cannot be any one of abc
- [a-zA-Z]: it represents the composition of an arbitrary letter;
- [0-9] digit
3. Simplified character set
- . any character
- \d is equivalent to [0-9]
- \D is not equivalent to [0-9]
- \s matches spaces
- \S matches non spaces
- \w matches letters, numbers, and underscores are equivalent to [0-9a-z_A-Z]
4. Boundary matching
- ^: match boundary start
- $: end of match boundary
5. By default, multiple characters can only be matched if a quantity unit is added
-
Expression? : the rule can appear 0 or 1 times
-
Expression +: the regular can appear one or more times
-
Expression *: the regular can appear 0 times or 1 times or more
-
Expression {n}: the rule can appear n times
-
Expression {n,}: the rule can appear more than n times
-
Expression {n,m}: the regularity can appear n times to m times
6. Logical expression: can connect multiple regularities
- Expression X| expression Y
- (expression): set an overall description for the expression, and you can set the quantity unit for the overall description;
File
Construction method: public File(String pathname)
Construction method: public File(File parent String child)
Create a new method: public boolean createNewFile() throws IOException
Determine whether the file exists: public boolean exists()
Delete file: public boolean delete()
Get parent path: public File getParentFile()
Create directory: public boolean mkdirs()
Whether the file is readable: public boolean canRead()
Whether the file is writable: public boolean canWrite()
Get file length: public long length()
Last modified: public long lastModified()
Is it a directory: public boolean isDirected()
Is it a file: public boolean isFile()
List directory contents: public File[] listFiles();
To modify all files in a directory:
package File; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; public class File1 { public static void main(String[] args) throws IOException { File f = new File("D:"+ File.separator + "mldn.txt"); System.out.println(f.getName()); System.out.println(f.length()); System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(f.lastModified())); System.out.println(f.canRead()); System.out.println(f.canWrite()); System.out.println(f.isDirectory()); System.out.println(f.isFile()); File f1 = new File("D:" + File.separator + "cn"); listDir(f1); // File result[] = f1.listFiles(); // for(int i = 0; i < result.length; i++){ // System.out.println(result[i]); // } } private static void listDir(File f){ if(f.isDirectory()){ File files[] = f.listFiles(); if(files != null) { for (int i = 0; i < files.length; i++) { listDir(files[i]); } } }else if(f.isFile()){ String fileName = f.getName(); if(fileName.contains(".")){ fileName = fileName.substring(0,fileName.lastIndexOf(".")) + ".txt"; }else{ fileName = fileName + ".txt"; } File newFile = new File(f.getParentFile(),fileName); f.renameTo(newFile); System.out.println(fileName); } } }
OutputStream class - byte stream
Method of OutputStream:
OutputStream structure:
FileOutputStream construction method:
Public fileoutputstream (file file) throws FileNotFoundException (overwrite)
FileOutputStream construction method:
Public fileoutputstream (file file Boolean append) throws FileNotFoundException (append)
InputStream class - byte stream
Method:
public int read(byte[] b)throws IOException
Writer character stream
Output operation method:
Output character array: public void write(char[] cbuf)throws IOException
Output string: public void write(String str)throws IOException
Reader character stream
`public int read(char[] byte) throws IOException``
OutputStream can be written without close(), while Writer can't, but Writer can force refresh with flush();
close() has the function of refreshing;
Writer makes use of buffer, which is faster;
- Byte stream does not use buffer, while byte stream uses buffer
Copy of files
package FileCopy; import java.io.*; class FileCo{ public static boolean copy(String srcFile,String desFile) throws Exception { File srcf = new File(srcFile); File desf = new File(desFile); if(!srcf.exists())return false; if(!desf.getParentFile().exists())desf.getParentFile().mkdirs(); InputStream inputStream = new FileInputStream(srcFile); OutputStream outputStream = new FileOutputStream(desFile); inputStream.transferTo(outputStream); // byte[] bytes = new byte[1024]; // int len = 0; // while((len = inputStream.read(bytes))!= -1){ // outputStream.write(bytes,0,len); // } inputStream.close(); outputStream.close(); return true; } } public class FileCopy { public static void main(String[] args) throws Exception { String srcFile = "I:"+ File.separator + "study.jpg"; String desFile = "C:" + File.separator + "Users" + File.separator + "Administrator" + File.separator + "Desktop" + File.separator + "carton.jpg"; long start = System.currentTimeMillis(); System.out.println(FileCo.copy(srcFile,desFile)); long end = System.currentTimeMillis(); System.out.println(end - start); } }
There is the copy function public long transferTo(OutputStream out)throws IOException
When writing the copy folder, an error was encountered. The error is that a list was omitted in recursion, resulting in
access denied
If this else is omitted, the folder will become a File to be copied, and access will be denied. For example, the File in the InputStream input stream needs to be a File
String head,File file2) throws Exception { //final String head = file.getPath(); if(file.isDirectory()){ File[] results = file.listFiles(); if(results != null){ for(int i = 0; i < results.length; i++)listDir(results[i],head,file2); } }else { String src = file.getPath(); String des = file2.getPath() + file.getPath().replace(head,""); fileCopy(src,des); } }
package FileCopy; import java.io.*; class FileCo{ public static boolean dirCopy(String srcFile,String desFile) throws Exception { File srcf = new File(srcFile); File desf = new File(desFile); listDir(srcf,srcFile,desf); try { return true; }catch (Exception e){ return false; } } public static void listDir(File file,String head,File file2) throws Exception { //final String head = file.getPath(); if(file.isDirectory()){ File[] results = file.listFiles(); if(results != null){ for(int i = 0; i < results.length; i++)listDir(results[i],head,file2); } }else { String src = file.getPath(); String des = file2.getPath() + file.getPath().replace(head,""); fileCopy(src,des); } } public static boolean fileCopy(String srcFile,String desFile) throws Exception { File srcf = new File(srcFile); File desf = new File(desFile); if(!srcf.exists())return false; if(!desf.getParentFile().exists())desf.getParentFile().mkdirs(); InputStream inputStream = new FileInputStream(srcf); OutputStream outputStream = new FileOutputStream(desf); inputStream.transferTo(outputStream); inputStream.close(); outputStream.close(); return true; // byte[] bytes = new byte[1024]; // int len = 0; // while((len = inputStream.read(bytes))!= -1){ // outputStream.write(bytes,0,len); // } } } public class FileCopy { public static void main(String[] args) throws Exception { String srcFile = "I:"+ File.separator + "study.jpg"; String desFile = "C:" + File.separator + "Users" + File.separator + "Administrator" + File.separator + "Desktop" + File.separator + "carton.jpg"; String srcFile1 = "I:" + File.separator + "happy"; String desFile1 = "I:" + File.separator + "fast"; long start = System.currentTimeMillis(); //System.out.println(FileCo.fileCopy(srcFile,desFile)); // File f = new File("I:" + File.separator + "QQ"); // FileCo.listDir(f,f.getPath()); System.out.println(FileCo.dirCopy(srcFile1,desFile1)); long end = System.currentTimeMillis(); System.out.println(end - start); } }
Memory operation flow
ByteArrayOutputStream: construction method – >public ByteArrayInputStream (byte[] buf)
ByteArrayInputStream: construction method – > public bytearrayeutputstream()
- Get data: public byte[] toByteArry();
- Get in the form of string: public String toString();
Pipeline flow and RandomAccessFile
Byte pipeline stream: PipedOutputStream and PipedInputStream.
Character pipeline flow: PipedWriter and PipedReader.
PipedOutputStream and PipedWriter are writers / producers / senders;
PipedInputStream and PipedReader are readers / consumers / receivers.
Byte pipeline flow
Here we only analyze byte pipeline flow. The principle of character pipeline flow is the same as byte pipeline flow, except that the bottom one is byte array storage and the other is char array storage.
java's pipeline input and output are actually implemented with a circular buffer number. Input stream PipedInputStream reads data from the circular buffer array, and output stream PipedOutputStream writes data to the circular buffer array. When the buffer array is full, the thread of the output stream PipedOutputStream will block; when the buffer array is empty, the thread of the input stream PipedInputStream will block.
Matters needing attention
Before using pipe flow, the following points need to be noted:
- Pipeline flow is only used to transfer information between multiple threads. If it is used in the same thread, it may cause deadlock;
- The input and output of the pipeline flow are in pairs. An output flow can only correspond to one input flow. Use the constructor or connect function to connect;
- A pair of pipeline streams contains a buffer, with a default value of 1024 bytes. To change the size of the buffer, you can use a constructor with parameters;
- When the buffer is empty, the read operation is blocked; when the buffer is full, the write operation is blocked;
- The pipeline is attached to the thread, so if the thread ends, the error "read dead end" will be reported even though the pipeline flow object is still there;
- The reading method of the pipeline flow is different from that of the normal flow. Only when the output flow is properly close d, can the output flow read the value of - 1.
RandomAccessFile:
Construction method: RandomAccessFile raf = newRandomAccessFile(File file, String mode);
The value of parameter mode can be r: readable, w: writable, rw: readable;
Member method:
seek(int index); the pointer can be moved to a certain position to start reading and writing;
Setlength (long length); reserve space for writing files:
BufferedReader
Read a row of data: public String readLine() throw IOException
Scanner
sc.useDelimiter("\n") set line feed
Object serialization
Implement the java.io.Serializable parent interface. As a serializable interface, this interface has no method like clonable, only represents one capability;
serialization and deserialization
Serialization: objectoutputstream OOS = new objectoutputstream (New fileoutputstream (save Fu file));
Deserialization: objectinputstream OO = new objectinputstream (New FileInputStream (save file));
If tarnsent is added, it will not be serialized into the document, and null will be assigned;
package File; import java.io.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Scanner; public class Sc { private static final File SAVE_FILE = new File("I:" + File.separator + "mldn.txt"); public static void main(String[] args) throws Exception { saveObject(new Person("xiao",22)); System.out.println(load()); } public static void saveObject(Object obj) throws Exception { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SAVE_FILE));//Streams used for serialization oos.writeObject(obj); oos.close(); } public static Object load() throws Exception { ObjectInputStream oos = new ObjectInputStream(new FileInputStream(SAVE_FILE));//Streams for deserialization Object obj = oos.readObject(); oos.close(); return obj; } } class Person implements Serializable{//Implement the interface to represent that the class can be serialized by objects private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
Collection interface
public boolean add(E e): append a data
public boolean add(E e): append a set of data
public void clear(): empty collection
Public Boolean contains (object o): to query whether data exists, equals() is required
Public Boolean contains (object o): to query whether data exists, equals() is required
public boolean remove(Object o): to delete data, you need equals() support
public Object[] toArray(): returns the collection as an array
Public Iterator < E > Iterator(): change the collection to Iterator interface and return
list interface
public E get(int index): get the number on the specified index
public E set(int index, E element): modify the specified index data
Public ListIterator < E > ListIterator(): return ListIterator interface
Three subclasses, ArrayList, LinkedList, Vector
ArrayList implements List,RandomAccess,Cloneable,Serializable – > array
- Saving data is storing data
- Can store duplicate data
When the length of the ArrayList set is not enough, a new array will be created and the original data will be copied;
When instantiating an ArrayList class object: no initial length is passed, an empty array is used by default. If you add data at this time, you will judge the current growth capacity (grow() method) and the default capacity size (10), and use a larger one to open a new array;
If the capacity is insufficient, it will grow in multiple ways, ` int newcapacity = oldcapacity + (oldcapacity > > 1);
When the estimated size is greater than 10, the parametric construction should be used;
LinkedList implements List,RandomAccess,Cloneable,Serializable – > linked list storage form
LinkdList can store null, and all nodes in LinkedList are saved with Node.
Vector implements List,RandomAccess,Cloneable,Serializable – > array
When Vector is initialized, it is created as a size of 10;
Vector's operation methods are thread safe, so the efficiency is not as high as ArrayList
Set extends Collection
When of() is used, an exception is thrown directly if duplicate elements are found in the collection.
In general, subclass is used to realize listing, HashSet and TreeSet
HashSet: save is unordered
TreeSet: sortable, custom class must inherit the comparable interface
Output:
ListIterator can output in reverse order, bidirectional;
public boolean hasPrevious(): judge whether there is a previous element
public E previous():: get the current element
Enumeration: dedicated to Vector.
Public Enumeration < E > elements():: get Enumeration
public boolean hasMoreElements(): determine whether there is next element
Public e nexterelement(): get current element
Map extends Map<K,V>,Cloneable,Serializbale,AbstractMap<K,V>
public V put(K key, V value): save data to the collection
public V get(Object key): query data by Key
Public Set < Map. Entry < K, V > > entryset: convert Map to Set set
Public Boolean containnskey (object K): query whether the specified key exists;
Public Boolean containnsvalue (object Value): query whether the specified Value exists;
Public Set < k > keyset(): convert the key in the Map to Set set Set;
HashMap: unordered, null able
Use put method: if the data exists, return the old Value; if not, return null;
Put method source code: a putVal() method will be called, hash() will be called for hash encoding, and a Node class will be saved;
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
When using nonparametric Construction: loadFactor property, the default content is 0.75f(static final float DEFAULT_LOAD_FACTOR = 0.75f)
Capacity expansion:
Static final int default ABCD initial ABCD capacity = 1 < < 4; / / aka 16 constant, default size is 16
- When the saved constant exceeds the threshold value (static final float default \ load \ factor = 0.75f), i.e. 16 * 0.75 = 12, the capacity expansion will be performed instead of waiting until it is full (16). 1-fold, 16, 32, 64 at a time.
working principle:
- HashMap data is saved by Node class, so it is proved that the data structure at this time can only be linked list or binary tree
- Therefore, there is a constant in it: static final int treeify_treehold = 8, which means that when the number of data is greater than 8, the linked list will be converted to a red black tree for storage, and when it is less than 8, the linked list will be used;
When using LinkedHashMap, all data stores are ordered and null key values can be saved.
Hashtable: synchronization method (thread safe), cannot store null
Stack extends Vector
- push(E item);
- Out of stack: pop();
Properties exdents Hashtable<Object,Object>
Only string is allowed
public String getPorperty(String key): get attribute
Public void store (OutputStream out, string comments) throws IOException: output attribute content
public void load(InputStream inStream)throws IOException: read attribute content through input stream
All Chinese will be transcoded automatically
reflex
Reflection and factory design mode:
import static java.lang.Class.forName; interface Imessage{ void send(); } interface IService{ void service(); } class Good implements IService{ public void service(){ System.out.println("Commodity service"); } } class StuMessage implements Imessage{ @Override public void send() { System.out.println("Students have classes!!"); } } class TeaMessage implements Imessage{ @Override public void send() { System.out.println("The teacher wants to teach!!"); } } class Factory { private Factory(){} public static <T>T getInstance(String className) throws Exception { T instance = null; instance = (T) Class.forName(className).getDeclaredConstructor().newInstance(); return instance; } } public class Reflect { public static void main(String[] args) throws Exception { Imessage msg = Factory.getInstance("Reflect.TeaMessage"); msg.send(); IService ser = Factory.getInstance("Reflect.Good"); ser.service(); } }
Reflection and single design mode:
Starved Chinese: an object will be instantiated when the class is loaded
class Single1{ private Single1(){} private static Single1 instance = new Single1(); public Single1 getInstance(){ return instance; } }
Lazy: only when you need an object can you produce a single object
class Single{ private Single(){} private static Single instance = null; public static Single getInstance(){ if(instance == null) instance = new Single(); return instance ; } }
Hungry Han style:
- Starved Chinese is thread safe (it will be initialized only when the class is loaded, not later)
- No lock, high execution efficiency
- This method is commonly used, but it is easy to generate garbage objects
- Class is initialized when it is loaded, wasting memory
- Based on the classloder mechanism, multi thread synchronization is avoided
- Instance is instantiated when the class is loaded. Although there are many reasons for class loading, most of them call getInstance method in the single instance mode, but it is not certain that there are other ways (or other static methods) to cause class loading. At this time, initialization of instance obviously does not achieve the effect of lazy loading.
Slacker:
- Non thread safe
- This is the most basic way of implementation. The biggest problem of this implementation is that it does not support multithreading. Because there is no lock synchronized, it is not strictly a singleton mode. In this way, lazyloading obviously does not require thread safety and does not work properly in multithreading
Modified lazy style:
class Single{ private Single(){} private static Single instance = null; public static synchronized Single getInstance(){ if(instance == null) instance = new Single(); return instance ; } }
Add synchronization to getInstance method.
However, at this time, the efficiency will be very low, such as the multi-threaded operating system. I think only one of 64 threads can access it. So as long as synchronization is added to the instantiation;
class Single{ private Single(){} private static Single instance = null; public static Single getInstance(){ synchronized(Single.class){ if(instance == null){ instance = new Single(); } } return instance ; } }
Get construction method:
Instantiation method substitution: clazz.getDeclaredConstructor().newInstance()
Get all construction methods: public constructor <? > [] getdeclaredconstructors() throws SecurityException
Get the specified constructor: public constructor < T > getdeclaredconstructor (class <? >... Parametertypes) throws nosuchmethodexception, SecurityException
Get all construction methods: public constructor <? > [] getconstructors() throws SecurityException
Get the specified constructor: public constructor < T > getconstructor (class <? >... Parametertypes) throws nosuchmethodexceptionsecurityexception
invoke()
Class loader
ClassLoader class:
public final ClassLoader getClassLoader
Network programming
Simple Echo model:
Server side
public class Service { public static void main(String[] args) throws Exception{ ServerSocket server = new ServerSocket(999); System.out.println("Let's connect the clients======"); Socket client = server.accept(); // Waiting for connection //Client input stream and output stream to client Scanner sc = new Scanner(client.getInputStream()); PrintStream out = new PrintStream(client.getOutputStream()); boolean flag = true; while(flag){ if(sc.hasNext()){ String str = sc.next().trim(); // Get messages from clients if (str.equalsIgnoreCase("byebye")){ out.println("bye~~~~~~~~"); flag = false; }else out.println("[Echo]" + str); // Output data to client } } sc.close(); out.close(); client.close(); server.close(); } }
Client
public class Client { public static void main(String[] args) throws Exception { Socket client = new Socket("localhost",999);//Connecting server host number plus terminal slogan Scanner input = new Scanner(System.in); //Get keyboard input object /** * Data transfer from the outside to this program is input * From this program to the outside, it is output */ Scanner sc = new Scanner(client.getInputStream()); //Get input stream (get output from server) PrintStream out = new PrintStream(client.getOutputStream());//(output to server) input.useDelimiter("\n"); sc.useDelimiter("\n"); boolean flag = true; while(flag){ System.out.println("Please enter the data to send"); if(input.hasNext()){ String str = input.next().trim(); // Input string str out.println(str); //Write string to server if(str.equalsIgnoreCase("byebye"))flag = false; if(sc.hasNext())System.out.println(sc.next()); // Get output from server } } input.close(); sc.close(); out.close(); client.close(); } }
Servers (multithreaded) that allow multiple clients to access:
class EchoThread implements Runnable{ private Socket client; public EchoThread(Socket client){ this.client = client; } @Override public void run() { Scanner sc = null; PrintStream out = null; try { sc = new Scanner(client.getInputStream()); out = new PrintStream(client.getOutputStream()); boolean flag = true; while(flag){ if(sc.hasNext()){ String str = sc.next().trim(); if(str.equalsIgnoreCase("byebye")){ out.println("bye~~~~~~"); flag = false; }else out.println("Echo" + str); } } } catch (IOException e) { e.printStackTrace(); }finally{ if(sc != null)sc.close(); if(out != null)out.close(); if(client != null) { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } } } public class Service { public static void main(String[] args) throws Exception{ ServerSocket server = new ServerSocket(999); System.out.println("Waiting for client connection======"); boolean flag = true; while(flag){ Socket client = server.accept(); new Thread(new EchoThread(client)).start(); } } }