Rename a file using Java

前端 未结 14 1019
感情败类
感情败类 2020-11-22 07:54

Can we rename a file say test.txt to test1.txt ?

If test1.txt exists will it rename ?

How do I rename it to the alrea

14条回答
  •  日久生厌
    2020-11-22 08:25

    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import static java.nio.file.StandardCopyOption.*;
    
    Path yourFile = Paths.get("path_to_your_file\text.txt");
    
    Files.move(yourFile, yourFile.resolveSibling("text1.txt"));
    

    To replace an existing file with the name "text1.txt":

    Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);
    

提交回复
热议问题