NIO

1.文件复制

package com.run.learn;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
/**
 * 可以使用System类的getProperties()方法来访问本地系统的文件编码格式,文件编码格式的属性名为file.encoding
 *
 */
public class NioLearn {
    public static void main(String[] args) {
        File f = new File("E:\ElsFk.java");
        try(FileChannel inChannel = new FileInputStream(f).getChannel();
                FileChannel outChannel = new FileOutputStream("E:\a.txt").getChannel();
        ){
            //將FileChannel里的全部映射成byteBuffer
            MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
            //使用GBK的字符集来创建解码器
            Charset charset = Charset.forName("GBK");
            //直接将buffer中的数据全部输出
            outChannel.write(buffer); 
            //复原limit,position的位置
            buffer.clear();
            //创建解码器对象
            CharsetDecoder decoder = charset.newDecoder();
            //使用编码器将ByteBuffer转换成CharBuffer
            CharBuffer charBuffer = decoder.decode(buffer);
            System.out.println(charBuffer);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
2.使用FileVisitor遍历文件和目录
files工具类提供了两个方法来遍历文件和子目录
walkFileTree(Path start,FileVistor<? super Path> visitor):遍历start路径下的所有文件和子目录
walkFileTree(Path start, Set<FileVisitOption> options,int maxDepth , FileVisitor<? super Paht> visitor):与上一个方法的功能类似,该方法最多遍历maxDepth深度的文件。
 
实际编程没必要为FileVistor的4个方法都提供实现,可以通过继承SimpleFileVisitor(FileVistor的实现类)
3.WatchService监听文件变化
package com.run.learn;

import java.nio.file.FileSystems;
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 AboutWatch {
	public static void main(String[] args) {
		try {
			//获取文件系统的WatchService对象
			WatchService ws = FileSystems.getDefault().newWatchService();
			//为C盘根路径注册监听
			Paths.get("C:/").register(ws, StandardWatchEventKinds.ENTRY_CREATE
					,StandardWatchEventKinds.ENTRY_MODIFY
					,StandardWatchEventKinds.ENTRY_DELETE);
			while(true){
				//获取下一个文件变化事件
				WatchKey key = ws.take();
				for (WatchEvent<?> event : key.pollEvents()) {
					System.out.println(event.context() + "文件发送了" + event.kind()+"事件!");
				}
				//重设WatchKey
				boolean valid = key.reset();
				//如果重设失败,退出监听
				if(!valid){
					break;
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
原文地址:https://www.cnblogs.com/judylucky/p/6991534.html