Rename a file using Java

前端 未结 14 804
感情败类
感情败类 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);
    
    0 讨论(0)
  • 2020-11-22 08:26

    This is an easy way to rename a file:

            File oldfile =new File("test.txt");
            File newfile =new File("test1.txt");
    
            if(oldfile.renameTo(newfile)){
                System.out.println("File renamed");
            }else{
                System.out.println("Sorry! the file can't be renamed");
            }
    
    0 讨论(0)
提交回复
热议问题