java 1.7 新io 实践 NIO2

Files 类使用

package com.xinyu.test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class FileTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        //Files创建,删除
//      Path path =Paths.get("D:/jun/xinyu.txt");
//      try {
//          Files.createFile(path);
//          Files.deleteIfExists(path);
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }

        //Files复制,移动

//      try {
//          Path path = Paths.get("D:/jun/psb (4).jpg");
//          Path target =Paths.get("D:/test/jun.jpg");
//          Path parent = target.getParent();
//          boolean exists = parent.toFile().exists();
//          if(!exists){
//              Files.createDirectories(parent);
//          }
////            Files.copy(path, target, StandardCopyOption.REPLACE_EXISTING);
//          Files.move(path, target, StandardCopyOption.REPLACE_EXISTING);
//          
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }

        //查看文件属性
//      Path path = Paths.get("D:/liebao/debug.log");
//      try {
//          System.out.println(Files.getLastModifiedTime(path));
//          System.out.println(Files.size(path));
//          System.out.println(Files.isDirectory(path));
//          System.out.println(Files.readAttributes(path, "*"));
//          System.out.println();
//          System.out.println();
//          System.out.println(19_12);
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }

        //简化的文件读写
//      Path path =Paths.get("D:/liebao/debug.log");
//      try {
//          List<String> readAllLines = Files.readAllLines(path,StandardCharsets.UTF_8);
//          for (String entry : readAllLines){
//              System.out.println(entry);
//          }
//          
//          byte[] readAllBytes = Files.readAllBytes(path);
//          System.out.println(new String(readAllBytes));
//          
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }

        //读取文件的最后几个字节
        Path path=Paths.get("D:/liebao/test.txt");
        try {
            FileChannel open = FileChannel.open(path, StandardOpenOption.READ);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //从第23个字节开始读
//          int read = open.read(buffer,open.size()-(open.size()-23));/
//          open.read(buffer, 2, 10);
//          System.out.println(new String(buffer.array()));
//          System.out.println(open.size());

            //下面的一直报错,不管了先
            ByteBuffer[] dsts = new ByteBuffer[12];
            System.out.println(dsts.length);
            System.out.println(open == null);
            open.read(dsts, 1, 3);

            System.out.println(dsts[0].array());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}

Paths类的使用:

package com.xinyu.test;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class PathTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Path  基本操作
//      Path path = Paths.get("D:/jun");
//      System.out.println(path.getFileName());
//      System.out.println(path.getFileSystem());
//      System.out.println(path.getNameCount());
//      System.out.println(path.getParent());

        //path 的合并
//      Path path = Paths.get("D:/");
//      Path resolve = path.resolve("jun");
//      System.out.println(resolve.getFileName());
//      System.out.println(resolve.getFileSystem());
//      System.out.println(resolve.getNameCount());
//      System.out.println(resolve.getParent());

        //从path到path2的相对路径,输出:..\cebdoc
//      Path path = Paths.get("D:/jun");
//      Path path2 = Paths.get("D:/cebdoc");
//      Path relativize = path.relativize(path2);
//      System.out.println(relativize);

        //path的一些其他操作,包括startWith,endWith
//      Path path = Paths.get("D:/jun");
//      Path path2 = Paths.get("D:/cebdoc");
//      boolean startsWith = path.startsWith(path2);
//      System.out.println(startsWith);

        //jdk1.7之后 path 和file是可以相互转换的
//      File file = new File("D:/jun");
//      Path path3 = file.toPath();
//      file =path3.toFile();

        //path遍历目录  只输出制定的文件  列出目录下的所有txt文件
//      Path path = Paths.get("D:\\jun");
//      try {
//          DirectoryStream<Path> stream = Files.newDirectoryStream(path,"*.txt");
//          for (Path entry : stream){
//              System.out.println(entry.getFileName());
//          }
//      } catch (IOException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }


        //path遍历目录,以及目录下的目录  找出是所有的doc文件
        class FindJavaVisitor extends SimpleFileVisitor<Path>{
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // TODO Auto-generated method stub
                if(file.toString().endsWith(".txt")){
                    System.out.println(file.getFileName());
                }
                return super.visitFile(file, attrs);
            }

        }
        Path path = Paths.get("D:\\software");
        try {
            Files.walkFileTree(path, new FindJavaVisitor());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }




    }

}

文件观察服务的使用
WatchService

package com.xinyu.test;

import java.io.IOException;
import java.nio.file.FileSystem;
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;

public class FilWatchServicesTest {
    public static void main(String[] args) {
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Path path =Paths.get("D:/jun");
            path.register(watchService,StandardWatchEventKinds.ENTRY_MODIFY);
            while (true) {
                WatchKey take = watchService.take();
                for (WatchEvent<?> event : take.pollEvents()) {
                    if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println("i is delete");
                    }
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        System.out.println("i is modify");
                    }

                }
                take.reset();

            }
        } catch (IOException | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
posted @ 2017-03-26 17:40  有点理想的码农  阅读(346)  评论(0编辑  收藏  举报