Rename a file using Java

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

    In short:

    Files.move(source, source.resolveSibling("newname"));
    

    More detail:

    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    

    The following is copied directly from http://docs.oracle.com/javase/7/docs/api/index.html:

    Suppose we want to rename a file to "newname", keeping the file in the same directory:

    Path source = Paths.get("path/here");
    Files.move(source, source.resolveSibling("newname"));
    

    Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:

    Path source = Paths.get("from/path");
    Path newdir = Paths.get("to/path");
    Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
    

提交回复
热议问题