Java复制、移动和删除文件
发布日期:2021-05-09 06:23:01 浏览次数:29 分类:博客文章

本文共 1041 字,大约阅读时间需要 3 分钟。

复制文件:

Files.copy(fromPath,toPath);

例如:

Files.copy(Paths.get("E:\\A.txt"), Paths.get("F:\\A.txt"));// 将E:\\A.txt复制到F:\\A.txt

这是Java 的API(注意:没有copy(String,String);的方法的!):

Modifier and Type Method Description
static long ( in,  target, ... options) Copies all bytes from an input stream to a file.
static long ( source,  out) Copies all bytes from a file to an output stream.
static  ( source,  target, ... options) Copy a file to a target file.

移动文件(复制并删除源文件):

Files.move(fromPath,toPath);

例如:

Files.move(Paths.get("E:\\A.txt"), Paths.get("F:\\A.txt"));//将E:\\A.txt移动到F:\\A.txt

如果目标路径已经存在,复制或移动将失败,抛出异常java.nio.file.FileAlreadyExistsException

覆盖已有的目标路径,使用StandardCopyOption.REPLACE_EXISTING;例如:

Files.move(Paths.get("E:\\A.txt"), Paths.get("F:\\A.txt"), StandardCopyOption.REPLACE_EXISTING);

复制所有的文件属性,使用StandardCopyOption.COPY_ATTRIBUTES。

删除文件:

Files.delete(path);

例如:

Files.delete(Paths.get("E:\\A.txt"));//删除E:\\A.txt

如果删除文件不存在,会抛出异常java.nio.file.NoSuchFileException。因此,可以使用deleteIfExists(path)方法:

boolean deleted = Files.deleteIfExists(path);

 

转载地址:https://www.cnblogs.com/sgh1023/p/10009498.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java实现将任何编码方式的txt文件以UTF-8编码方式转存
下一篇:内联汇编很可怕吗?看完这篇文章,终结它!

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月10日 18时13分23秒