Rename a file using Java

前端 未结 14 1017
感情败类
感情败类 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:08

    Copied from http://exampledepot.8waytrips.com/egs/java.io/RenameFile.html

    // File (or directory) with old name
    File file = new File("oldname");
    
    // File (or directory) with new name
    File file2 = new File("newname");
    
    if (file2.exists())
       throw new java.io.IOException("file exists");
    
    // Rename file (or directory)
    boolean success = file.renameTo(file2);
    
    if (!success) {
       // File was not successfully renamed
    }
    

    To append to the new file:

    java.io.FileWriter out= new java.io.FileWriter(file2, true /*append=yes*/);
    

提交回复
热议问题