Rename a file using Java

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

    For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.

    Example:

    File newFile = new File(oldFile.getParent(), "new-file-name.txt");
    Files.move(oldFile.toPath(), newFile.toPath());
    

    The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.

    EDIT: I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.

提交回复
热议问题