话不多说,直接上代码
1.使用FileChannel的transferTo方法
try(FileChannel from = new FileInputStream("dome.txt").getChannel(); FileChannel to = new FileOutputStream("to.txt").getChannel(); ) { long size = from.size(); //left变量表示还剩多少字节,每次最多拷贝2g for (long left=size;left>0;){ left-=from.transferTo((size-left),left,to); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
2.使用Files类的copy方法
//获取该文件地址的path,其中参数如果是绝对路径则是绝对路径。如果不是绝对路径则是相对路径,如下 Path path=Paths.get("dome.txt"); //1.判断文件是否存在 System.out.println(Files.exists(path)); //2.创建一级目录,如果是多级目录会报错 Path path1=Paths.get("d:/toot"); try { Files.createDirectory(path1); } catch (IOException e) { e.printStackTrace(); } //3.创建多级目录 Path path2=Paths.get("d:/root/ta"); try { Files.createDirectories(path2); } catch (IOException e) { e.printStackTrace(); } //3.copy文件,其中第一个参数是源文件,第二个参数是是目标文件,第三个参数是如果目标文件已经存在,覆盖该文件,如果不需要可以不填 Path path3=Paths.get("dome1.txt"); try { Files.copy(path,path3, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } //4.删除文件,和删除文件目录,删除目录时如果目录中还要文件,则会报错,当然没有文件和目录也会失败 try { Files.delete(path); } catch (IOException e) { e.printStackTrace(); }
3.copy整个目录的东西及其子目录
//记录目录的数量 AtomicInteger dirCount = new AtomicInteger(); //记录文件的数量 AtomicInteger fileCount = new AtomicInteger(); //需要复制的文件目录 Path path = Paths.get("D:\\test"); //目标文件起始目录 Path path1 = Paths.get("D:\\test1"); try { Files.walkFileTree(path,new SimpleFileVisitor<Path>(){ @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { dirCount.incrementAndGet(); //遍历到目录处理方式 if(path.toString().equals(dir.toString())){ Files.createDirectories(path1); }else { String replace = dir.toString().replace(path.toString(), path1.toString()); Files.createDirectories(Paths.get(replace)); } return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { //遍历到文件处理方式 fileCount.incrementAndGet(); String replace = file.toString().replace(path.toString(), path1.toString()); Files.copy(file,Paths.get(replace),StandardCopyOption.REPLACE_EXISTING); return super.visitFile(file, attrs); } }); } catch (IOException e) { e.printStackTrace(); } System.out.println(dirCount); System.out.println(fileCount);
4.另外一种方式实现copy目录
//需要复制的文件目录 String resource="D:\\test"; //目标文件起始目录 String target="D:\\test1"; //遍历文件目录 try { Files.walk(Paths.get(resource)).forEach(path -> { //得到文件目录 String targetName=path.toString().replace(resource,target); //是文件目录 if(Files.isDirectory(path)){ try { Files.createDirectories(Paths.get(targetName)); } catch (IOException e) { e.printStackTrace(); } } //是文件 if(Files.isRegularFile(path)){ try { Files.copy(path,Paths.get(targetName), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } } }); } catch (IOException e) { e.printStackTrace(); }