New Features of JDK 7 Summary instance code parsing, new features of jdk
1. switch supports String parameters.
/***** Switch supports the String parameter jdk7 * @ author huangjiawei */public class SwitchTest {public static void switchTest (String arg) {switch (arg) {case "Lisa ": system. err. println ("I'm Lisa! "); Break; case" Mike ": System. err. println (" I'm Mike! "); Break; default: System. err. println (" I'm your only one! "); Break ;}} public static void main (String [] args) {switchTest (" Lisa "); // I'm Lisa! SwitchTest ("Mike"); // I'm Mike! SwitchTest (""); // I am your only one! }}
Switch enumeration supported
/*** Switch enumeration supports jdk5 * @ author huangjiawei **/public class SwitchMonthTest {public static void SwithMonthTest (Month month) {switch (month) {case JANUARY: System. err. println ("this is July"); break; case FEBRUARY: System. err. println ("this is July"); break; case MARCH: System. err. println ("this is July"); break;} public static void main (String [] args) {SwithMonthTest (Month. JANUARY); // This is the JANUARY SwithMonthTest (Month. FEBRUARY); // This is the FEBRUARY SwithMonthTest (Month. MARCH); // This is July }}
2. Improvement of digital literal volume
2.1. Before Java 7, it supports decimal (1234), octal (01234), and hexadecimal (0x1234)
Java 8 supports binary (0B11110001)
2.2. Underlines can be used to separate _
Public class BinaryTest {private static int a = 16; // decimal private static int B = 020; // private static int c = 0x10; // hexadecimal private static int d = 0b00000000000; // binary, 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. Automatic Resource Shutdown
In Java, many resources need to be disabled after they are used. For example, InputStream, Writer, Sockets, and Connection. Before Java 7, the close () method is usually called. in Java 7, you can ignore whether it is disabled or not. We can use the try-with-resources code block.
Import java. io. bufferedReader; import java. io. fileReader; public class TryTest {/** accept the path of 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 "" ;}/ ** accept the path of a file Java7 */public static String tryTest1 (String path) {/** when the try statement block ends, FileInputStream is automatically disabled. 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, capture multiple exceptions must have multiple catch clauses. in Java 7, we can write as follows:
Import java. util. date;/*** multiple catch statements always execute the first matched catch exception, many catch scripts will be ignored later * @ 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 (); // if an exception is thrown here, the following statement will not be executed! Int result = a/B; // The System is not executed. err. println (result); // will not execute} 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 java 7, the type must be declared before and after <> */List <String> list = new ArrayList <String> (); /** java 7, after <> does not need to declare the type, automatically according to the previous <> deduce its type */List <String> list1 = new ArrayList <> ();}
6. Enhanced file systems
Java 7 launched a new NIO2.0 API to change the inconvenience caused by file management. nio. using common types such as Path, Paths, Files, WatchService, and FileSystem under the file package can simplify the coding of file management by developers.
6.1 Path interface and Paths class
Some functions of the Path interface can be equivalent to the File class in the java. io package. Of course, these functions are limited to read-only operations. In the actual development process, developers can use the Path interface and Paths class to obtain a series of context information about the file.
- Int getNameCount (): Get the number of nodes in the current file
- Path getFileName (): get the name of the current file
- Path getRoot (): Get the root directory of the current file
- Path getParent (): gets the parent-level associated directory of the current file
Use the Path interface and Paths 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 Parent Association Directory:" + path. getParent (); // file parent-level associated Directory: C: \ Users \ huangjiawei \ Desktop }}
6.2. Files class
The Path interface and the Paths class can be used together to conveniently access the context information of the target file. Of course, all these operations are read-only. If developers want to perform other non-read-only operations on Files, such as file creation, modification, and deletion, they can use the Files type for operations.
Common Methods for Files are as follows:
- Path createFile (): Creates a new file in the specified target directory.
- Void delete (): delete a file or folder in the specified target path.
- Path copy (): copy the file in the specified target Path to another file.
- Path move (): transfers the file in the specified target Path to another Path and deletes the source file.
Example of copying and pasting Files using the Files type:
Files.copy(Paths.get("/test/src.xml"), Paths.get("/test/target.xml"));
Using the Files type to manage Files is more convenient and simple than the traditional I/O method. Because the specific operation implementation will be handed over to NIO2.0 API, developers do not need to pay attention to it.
6.3. WatchService
Java 7 also provides developers with a new set of file system functions, that is, file monitoring. A lot of friends may not know the significance and purpose of file monitoring, so please think back to the Web Container after debugging into the 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 a file change, the system automatically adapts to these "changes" and reloads the internal load. The hot release function of Web containers is also based on the file monitoring function. Therefore, we have to admit that the appearance of file monitoring is of great significance for Java file systems.
File monitoring is event-driven, and event triggering is a prerequisite for monitoring. Developers can use the three literal constants provided by the StandardWatchEventKinds type under the java. nio. file package to define the monitoring event type. It is worth noting that the monitoring event must be registered with the WatchService instance.
Monitoring events provided by StandardWatchEventKinds:
- ENTRY_CREATE: file or folder creation event;
- ENTRY_DELETE: file or folder deletion event;
- ENTRY_MODIFY: file or folder pasting event;
A complete example of using the WatchService class to implement file monitoring:
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 ();/* registers all event types of file monitoring. */path. register (watchService, StandardWatchEventKinds. ENTRY_CREATE, StandardWatchEventKinds. ENTRY_DELETE, StandardWatchEventKinds. ENTRY_MODIFY);/* Cyclic Monitoring file. */while (true) {WatchKey watchKey = watchService. take ();/* all files that trigger events iteratively */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 ();}}
The preceding program example shows that it is very simple and convenient to use the WatchService interface for file monitoring. First, we need to define the target monitoring path, and then call the FileSystems newWatchService () method to create the WatchService object. Next, we need to use the register () method of the Path interface to register the WatchService instance and monitor the event. When all these basic job layers are ready, we will write a peripheral Real-time Monitoring loop. Finally, iterate the WatchKey to obtain all the files that trigger the monitoring event.
Now I finally know the basic principle of the so-called dev-tools hot update in spring boot! In the past, JDK provided such an API.
Summary
The above is the sample code parsing of the new features of JDK 7 introduced by the small editor. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!