background image

 
Path   source   =   Paths.get   ("C:\\My   Documents\\Stuff.txt");Path   target   = 
Paths.get ("D:\\Backup\\MyStuff.txt");Files.copy (source, target);
 

 

  经常的,在拷贝文件的过程中你可能希望指定一些操作设置。在 Java7 里,你可以
通过使用 StandardCopyOption enum 来设置这些属性。下面看一个例子。
  
import static java.nio.file.StandardCopyOption.*;     Path source = Paths.get 
("C:\\My   Documents\\Stuff.txt");

 

 

Path   target   =   Paths.get 

("D:\\Backup\\MyStuff.txt");  Files.copy (source, target, REPLACE_EXISTING);
 
    拷 贝 操 作 时 可 以 使 用 的 属 性 还 包 括 COPY_ATTRIBUTES ( 保 留 文 件 属 性 )   和 
ATOMIC_MOVE(确保移动事务操作的成功,否则进行回滚)。

 

  移动文件的操作跟拷贝很相似,使用 Files.move (Path source, Path target) 方法。

 

    同 样 , 你 也 可 以 指 定 移 动 操 作 的 属 性 , 使 用 Files.move (Path source, Path 
target, CopyOptions...) 方法里的参数来设置。
 
  import   static   java.nio.file.StandardCopyOption.*;Path   source   =   Paths.get 
("C:\\My

 

Documents\\Stuff.txt");Path

 

target

 

=

 

Paths.get 

("D:\\Backup\\MyStuff.txt");Files.move   (source,   target,   REPLACE_EXISTING, 
COPY_ATTRIBUTES);
 

 

  可以看出,新的用于文件操作的 NIO.2 API 非常便于使用。参考英文原文:
http://www.java7developer.com/blog/?p=334