1. Switch supports String as parameters
/*** * switch supports string parameters jdk7 * @author huangjiawei */public class SwitchTest { public static void switchTest(String arg) { switch (arg) { case "Lisa": System.err.println("I am Lisa!"); break; case "Mike": System.err.println("I am Mike!"); break; default: System.err.println("I am your only!"); break; } } public static void main(String[] args) { switchTest("Lisa");//I am Lisa! switchTest("Mike");//I am Mike! switchTest("");//I am your only one! }}Switch enumeration support
/** * switch enumeration supports jdk5 * @author huangjiawei * */public class SwitchMonthTest { public static void SwithMonthTest(Month month) { switch (month) { case JANUARY: System.err.println("This is January"); break; case FEBRUARY: System.err.println("This is February"); break; case MARCH: System.err.println("This is March"); break; } } public static void main(String[] args) { SwithMonthTest(Month.JANUARY);//This is January SwithMonthTest(Month.FEBRUARY);//This is February SwithMonthTest(Month.MARCH);//This is March}}2. Improvement of numeric literals
2.1. Before Java7, it supports decimal (1234), octal (01234), and hexadecimal (0x1234)
Java 8 supports binary (0B11110001)
2.2. Can be separated by underscore_
public class BinaryTest { private static int a = 16;//decimal private static int b = 020;//octal private static int c = 0x10;//hexadecimal private static int d = 0b0001_0000;//binary, use delimiters to separate public static void main(String[] args) { System.err.println(a);//16 System.err.println(b);//16 System.err.println(c);//16 System.err.println(d);//16 }}3. Resources are automatically closed
In Java, there are many resources that need to be closed after they are used. Take a chestnut, InputStream, Writer, Sockets, Connection, etc. Before Java 7, it usually displays the close() method. In Java 7, you can ignore whether it is not closed. We can use the try-with-resources code block.
import java.io.BufferedReader;import java.io.FileReader;public class TryTest { /* * Accept the path to a file before Java 7*/ public static String tryTest(String path) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(path)); return br.readLine(); } catch (Exception e) { System.err.println("BufferedReader Exception" + e); } finally { if (br != null) { try { br.close(); br.ready();//The stream has been closed, an exception is thrown here} catch (Exception e) { System.err.println("BufferedReader close Exception" + e); } } } return ""; } /* * The path to accept a file Java7 */ public static String tryTest1(String path) { /* * When the try statement block runs, FileInputStream will be automatically closed. This is because FileInputStream implements the java.lang.AutoCloseable interface in java. * All classes that implement this interface can be used in the try-with-resources structure. */ try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } catch (Exception e) { System.err.println("BufferedReader Exception" + e); } return ""; } public static void main(String[] args) { tryTest("C://Users//huangjiawei//Desktop//my-release-key.keystore"); tryTest1("C://Users//huangjiawei//Desktop//my-release-key.keystore"); }}4. Catch multiple exceptions
Before Java 7, multiple catch clauses must be included to catch multiple exceptions. In Java 7, we can write this way:
import java.util.Date;/** * Multiple catch statements will only execute the first catch exception that matches. No matter how many catches there are, they will be ignored* @author huangjiawei * */public class CatchTest { /* * Before java 7*/ public static void CatchTest() { int a = 100; int b = 0; Date date = null; try { System.err.println(date.getTime());//Exception is thrown here, and the following statement will not be executed! int result = a/b;//System.err.println(result);//Not executed}catch(NullPointerException e) { System.err.println(e);//java.lang.NullPointerException }catch(ArithmeticException e){ System.err.println(e); }catch (Exception e) { System.err.println(e); } } /* * java 7 */ public static void CatchTest1() { int a = 100; int b = 0; Date date = null; try { int result = a/b; System.err.println(result); System.err.println(date.getTime()); }catch(ArithmeticException | NullPointerException e) { System.err.println(e);//java.lang.ArithmeticException: / by zero } } public static void main(String[] args) { CatchTest(); CatchTest1(); }}5. Instance creation type inference
import java.util.ArrayList;import java.util.List;public class TypeTest { /* * Before and after java 7, both types must be declared*/ List<String> list = new ArrayList<String>(); /* * java 7, after <> does not need to declare the type, and its type will be automatically inferred based on the previous <>*/ List<String> list1 = new ArrayList<>();}6. Enhanced file system
Java7 has launched a new NIO2.0 API to change the inconvenience against file management, so that using commonly used types such as Path, Paths, Files, WatchService, FileSystem and other products under the java.nio.file package can greatly simplify developers' coding work on file management.
6.1 Path interface and Paths class
Some functions of the Path interface can actually be equivalent to the File class under the java.io package. Of course, these functions are limited to read-only operations. In actual development, developers can use the Path interface and the Paths class to obtain a series of context information of the file.
Use the Path interface and Paths type to obtain file information:
import java.nio.file.Path;import java.nio.file.Paths;public class PathPathsTest { public static void main(String[] args) { Path path = Paths.get("C:////Users///huangjiawei////Desktop////my-release-key.keystore"); System.out.println("Number of file nodes:" + path.getNameCount()); //Number of file nodes: 4 System.out.println("File name:" + path.getFileName()); //File name: my-release-key.keystore System.out.println("File root directory:" + path.getRoot()); //File root directory: C:/System.out.println("File superior association directory:" + path.getParent()); //File superior association directory: C:/Users/huangjiawei/Desktop }}6.2. Files class
Using the Path interface and the Paths class can easily access the context information of the target file. Of course, these operations are all read-only. If developers want to perform other non-read-only operations on files, such as creation, modification, deletion, etc., they can use the Files type to operate.
Common methods of Files type are as follows:
Example of copying and pasting files using Files type:
Files.copy(Paths.get("/test/src.xml"), Paths.get("/test/target.xml"));Using Files type to manage files is more convenient and simple than traditional I/O methods. Because the specific operation implementation will be handed over to the NIO2.0 API, developers do not need to pay attention.
6.3. WatchService
Java7 also provides developers with a new set of file system functions, namely file monitoring. There may be many friends here that don’t know what the significance and purpose of file monitoring is. So please recall the web container that has been debugged into a hot release function. When the project is iterated and re-deployed, developers do not need to manually restart it because once the web container detects that the file changes, it will automatically adapt to these "changes" and reload internally. The hot publishing function of web containers is also based on file monitoring function, so it has to be admitted that the emergence of file monitoring function is of great significance to the Java file system.
File monitoring is event-driven, and event triggering is a prerequisite for monitoring. Developers can use the 3 literal constants provided by the StandardWatchEventKinds type under the java.nio.file package to define monitoring event types. It is worth noting that monitoring events need to be registered with the WatchService instance.
Monitoring events provided by the StandardWatchEventKinds type:
Complete example of implementing file monitoring using the WatchService class:
import java.nio.file.FileSystems;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardWatchEventKinds;import java.nio.file.WatchEvent;import java.nio.file.WatchKey;import java.nio.file.WatchService;/** * File monitoring system* @author huangjiawei */public class WatchViewTest { public static void testWatch() { /* Monitor target path*/ Path path = Paths.get("C://Users//huangjiawei//Desktop"); try { /* Create a file monitoring object. */ WatchService watchService = FileSystems.getDefault().newWatchService(); /* Register all event types for file monitoring. */ path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); /* Loop monitoring file. */ while (true) { WatchKey watchKey = watchService.take(); /* Iterate over all files that trigger the event*/ for (WatchEvent<?> event : watchKey.pollEvents()) { System.out.println(event.context().toString() + " Event type: " + event.kind()); } if (!watchKey.reset()) { return; } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { testWatch(); }} Through the above program examples, we can see that using the WatchService interface for file monitoring is very simple and convenient. First, we need to define the target monitoring path, and then call the newWatchService() method of FileSystems type to create a WatchService object. Next, we need to use the register() method of the Path interface to register the WatchService instance and monitor events. When all these basic working layers are ready, we write a peripheral real-time monitoring cycle. Finally, iterate over WatchKey to get all files that trigger monitoring events.
Now I finally know the basic principle of the so-called dev-tools hot update in spring boot! It turns out that JDK provides such APIs.
Summarize
The above is the code analysis of the JDK 7 new features brief introduction by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!