Java復制、移動和刪除文件


復制文件:

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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM