欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java复制、移动和删除文件

程序员文章站 2023-12-26 22:34:03
复制文件: 例如: 这是Java 的API(注意:没有copy(String,String);的方法的!): 移动文件(复制并删除源文件): 例如: 如果目标路径已经存在,复制或移动将失败,抛出异常java.nio.file.FileAlreadyExistsException。 覆盖已有的目标路径 ......

复制文件:

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 copy(inputstream in, path target, copyoption... options) copies all bytes from an input stream to a file.
static long copy(path source, outputstream out) copies all bytes from a file to an output stream.
static path copy(path source, path target, copyoption... 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);

 

上一篇:

下一篇: