Files:轻松复制、移动、删除或处理文件的工具类,有你需要的所有方法

    1. public class FilesDemo {
    2. public static void main(String[] args) throws IOException {
    3. Path path = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
    4. //Path file = Files.createFile(path);
    5. //System.out.println(file);
    6. Files.delete(path);
    7. }
    8. public static void copy() throws IOException {
    9. Path source = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
    10. Path target = Paths.get("D:/demo.txt");
    11. //copy 可以设置选项 move方法类似
    12. Files.copy(source,target);
    13. }
    14. public static void read(){
    15. Path file = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
    16. try(BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)){
    17. String line;
    18. while ((line = reader.readLine())!=null){
    19. System.out.println(line);
    20. }
    21. }catch (IOException e){
    22. }
    23. }
    24. public static void write(){
    25. Path file = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
    26. try(BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.WRITE)){
    27. //从头写
    28. //writer.write("hello world");
    29. writer.append("hello world");
    30. }catch (IOException e){
    31. }
    32. }
    33. //简化读写
    34. public static void simpleRead() throws IOException{
    35. Path file = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
    36. List<String> allLines = Files.readAllLines(file, StandardCharsets.UTF_8);
    37. for (String line : allLines) {
    38. System.out.println(line);
    39. }
    40. }
    41. public static void simpleRead2() throws IOException{
    42. Path file = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava/bak.txt");
    43. byte[] bytes = Files.readAllBytes(file);
    44. System.out.println(new String(bytes));
    45. }
    46. }

    WatchService:用来监视文件或目录的核心类,不管它们有没有变化

    1. import java.io.IOException;
    2. import java.nio.file.*;
    3. import static java.nio.file.StandardWatchEventKinds.*;
    4. public class WatchServiceDemo {
    5. private static boolean shutdown = false;
    6. public static void main(String[] args) {
    7. try {
    8. WatchService watcher = FileSystems.getDefault().newWatchService();
    9. //监听D盘根目录
    10. Path dir = FileSystems.getDefault().getPath("D:/");
    11. WatchKey key = dir.register(watcher, ENTRY_CREATE,ENTRY_DELETE);
    12. while (!shutdown) {
    13. key = watcher.take();
    14. for (WatchEvent<?> event : key.pollEvents()) {
    15. //如果有修改 则发出通知
    16. if (event.kind() == ENTRY_CREATE) {
    17. System.out.println("有文件创建");
    18. }
    19. if (event.kind() == ENTRY_DELETE) {
    20. System.out.println("有文件删除");
    21. }
    22. }
    23. key.reset();
    24. }
    25. } catch (IOException | InterruptedException e) {
    26. System.out.println(e.getMessage());
    27. }
    28. }
    29. }