Java用NIO流拷贝文件夹中所有文件

    科技2022-07-21  116

    Java用NIO拷贝一个文件夹,包括文件夹中所有文件

    通过NIO流拷贝文件夹中所有文件,包括使用将来式显示操作读取文件,代码如下:

    import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.concurrent.Future; public class K { @Test public void copyDirectory() throws IOException { Path path= Paths.get("E:\\edraw"); //遍历整个文件 Files.walkFileTree(path,new SimpleFileVisitor<Path>(){ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // 取出文件的每个目录 String srcPath=file.getParent().toString(); String desPath=srcPath.replaceFirst("E:","D:"); System.out.println(desPath); //在D盘创建目录 Files.createDirectories(Paths.get(desPath));//目录创建成功,但还在没有文件 //在目录下创建相应文件 String filePath=desPath+"\\"+file.getFileName(); if(!Files.exists(Paths.get(filePath))){ Files.createFile(Paths.get(filePath)); } //之后塞内容 //读文件 AsynchronousFileChannel asr=AsynchronousFileChannel.open(file,StandardOpenOption.READ); ByteBuffer buffer=ByteBuffer.allocate((int)Files.size(file));//开拷贝文件大小的内存 Future<Integer> rfuture =asr.read(buffer,0); ByteBuffer b1=ByteBuffer.wrap(buffer.array(),0,buffer.limit()); buffer.clear(); //写文件 AsynchronousFileChannel asw=AsynchronousFileChannel.open(Paths.get(filePath),StandardOpenOption.WRITE); Future<Integer> wfuture =asw.write(b1,0); while(!rfuture.isDone()||!wfuture.isDone()){ System.out.println("正在读写"+" "+file.getFileName()+" "+"文件"); } //完成后关闭 if(rfuture.isDone()&&wfuture.isDone()){ asw.close(); asr.close(); b1.clear(); System.out.println("完成"); } return super.visitFile(file, attrs); } }); } }
    Processed: 0.010, SQL: 8