企业级应用系统(J2EE)开发技术Java

Java NIO文件操作--相关类

2018-07-21  本文已影响2人  消失er

Buffer类

     CharBuffer charBuffer = CharBuffer.allocate(8);
        charBuffer.capacity();
        charBuffer.limit();
        charBuffer.position(); 

FileChannel类

    FileChannel fileChannelIn = fileInputStream.getChannel();
        FileChannel fileChannelOut = fileOutputStream.getChannel();
        MappedByteBuffer mappedByteBuffer = fileChannelIn.map(MapMode.READ_ONLY, 0, filein.length());
        fileChannelOut.write(mappedByteBuffer);

文件锁FileLock

    fileChannel = new FileOutputStream("a.txt").getChannel();
            FileLock fileLock = fileChannel.tryLock();
            Thread.sleep(10000);//文件处理
            fileLock.release();

FileVisitor

public static void main(String[] args) throws IOException {
        Files.walkFileTree(Paths.get("D:\\"),new SimpleFileVisitor<Path>(){

            @Override
            public FileVisitResult preVisitDirectory(Path dir,
                    BasicFileAttributes attrs) throws IOException {
                System.out.println("正在访问的路径="+dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file,
                    BasicFileAttributes attrs) throws IOException {
                if (file.endsWith("FileVisitorTest.java")) {
                    System.out.println("找到目标文件");
                    return FileVisitResult.TERMINATE;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc)
                    throws IOException {
                return super.visitFileFailed(file, exc);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                    throws IOException {
                System.out.println("访问结束");
                return super.postVisitDirectory(dir, exc);
            }

        });
    }

如示例,可以使用FileVisitor 进行磁盘文件查找。

WatchService

public static void main(String[] args) {
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            Paths.get("D:\\").register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
            while(true){
                WatchKey key = watchService.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    System.out.println(event.context()+ "发生了"+event.kind()+"事件");
                }
                boolean vaild = key.reset();//重设WatchKey
                if (!vaild) {//如果重设失败,退出监听
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

    }

访问文件属性BasicFileAttributeView

public static void main(String[] args) {
        Path testPath = Paths.get(".\\src\\com\\yin\\nio\\AttributeViewTest.java");
        BasicFileAttributeView basicView = Files.getFileAttributeView(testPath,
                BasicFileAttributeView.class);
        try {
            BasicFileAttributes basicFileAttributes = basicView.readAttributes();
            PrintStr("创建时间:"+new Date(basicFileAttributes.creationTime().toMillis()).toLocaleString());
            PrintStr("最后访问时间:"+new Date(basicFileAttributes.lastAccessTime().toMillis()).toLocaleString());
            PrintStr("最后修改时间:"+new Date(basicFileAttributes.lastModifiedTime().toMillis()).toLocaleString());
            PrintStr("文件大小:"+basicFileAttributes.size());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }   
    private static void PrintStr(String str){
        System.out.println(str);
    }




Java NIO2(AIO)

JDK1.7 NIO2主要改进了Classic I/O中java.io.File类对文件操作的局限性
NIO2还带来了真正意义上的Asynchronous I/O(异步I/O),具体实现分为文件Asynchronous I/O与网络传输Asynchronous I/O。因此NIO2也称为AIO。

NIO2 在 File 操作方面的升级
文件读写 Asynchronous I/O

NIO2通过AsynchronousFileChannel提供了异步读写文件的功能。通过AsynchronousFileChannel异步读写文件有CompletionHandler与Future两种方式。

Java 异步 I/O 网络通信实现

NIO2通过引入AsynchronousSocketChannel与AsynchronousServerSocketChannel实现了异步I/O网络通信模型。

上一篇 下一篇

猜你喜欢

热点阅读