7.5 Java新版本特性
7.5.1 Java 7
Map<String, List<String>> map = new HashMap<>();try (BufferedReader br = new BufferedReader(new FileReader("/data/data.txt"))) { br.read(); ... }String type = "text"; switch (type){ case "text": System.out.println("text type"); break; case "image": System.out.println("image type"); break; }try { ... } catch (FileNotFoundException | AccessException e) { e.printStackTrace(); }Path path = Paths.get("/data/test.dat"); Path path1 = FileSystems.getDefault().getPath("/data", "test.dat");if(!Files.exists(path)){ Files.createFile(path); } BufferedReader reader = Files.newBufferedReader(path1, StandardCharsets.UTF_8); //获取文件的BufferedReader来读取文件内容 BufferedWriter writer = Files.newBufferedWriter(Paths.get("/data/test.txt"), StandardCharsets.UTF_8);////获取文件的BufferedWriter来写文件Path dir = Paths.get("/data"); DirectoryStream<Path> stream = Files.newDirectoryStream(dir) for(Path e : stream){ System.out.println(e.getFileName()); } Stream<Path> stream = Files.list(dir); Iterator<Path> it = stream.iterator(); while(it.hasNext()){ Path curPath = it.next(); System.out.println(curPath.getFileName()); }Files.copy(Path source, Path target, CopyOption options); Files.copy(InputStream in, Path target, CopyOption options); Files.copy(Path source, OutputStream out);
WatchService watchService = FileSystems.getDefault().newWatchService(); //监控目录下的文件变动 Paths.get("[dirPath]").register(watchService, ENTRY_MODIFY, ENTRY_CREATE, ENTRY_DELETE); Executors.newSingleThreadExecutor().execute(() -> { while (true) { // 等待直到获得事件信号 WatchKey signal; try { signal = watchService.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event : signal.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } WatchEvent<Path> ev = (WatchEvent<Path>) (event); if (kind == ENTRY_MODIFY) { System.out.println(ev.context().getFileName() + "content changed"); } } // 为监控下一个通知做准备 signal.reset(); } });int i = 0b111; int j = 1_000_000;
7.5.2 Java 8
7.5.3 Java 9
7.5.4 Java10
7.5.5 Kotlin
Last updated
