Rename a file using Java

495,160

Solution 1

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*/);

Solution 2

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);

Solution 3

You want to utilize the renameTo method on a File object.

First, create a File object to represent the destination. Check to see if that file exists. If it doesn't exist, create a new File object for the file to be moved. call the renameTo method on the file to be moved, and check the returned value from renameTo to see if the call was successful.

If you want to append the contents of one file to another, there are a number of writers available. Based on the extension, it sounds like it's plain text, so I would look at the FileWriter.

Solution 4

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.

Solution 5

Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)

  String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
  File newFile = new File(newFilePath);

  try {
    FileUtils.moveFile(oldFile, newFile);
  } catch (IOException e) {
    e.printStackTrace();
  }
Share:
495,160

Related videos on Youtube

Jonas Czech
Author by

Jonas Czech

Cruising through space and time ¯\(ツ)/¯

Updated on March 25, 2022

Comments

  • Jonas Czech
    Jonas Czech about 2 years

    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 already existing test1.txt file so the new contents of test.txt are added to it for later use?

    • user207421
      user207421 almost 9 years
      Your last paragraph does not describe a rename operation at all. It describes an append operation.
  • Thomas Owens
    Thomas Owens almost 15 years
    No idea, but it's the exact same thing that Pierre posted, without the source code...
  • Stephane Grenier
    Stephane Grenier over 14 years
    This code won't work in all cases or platforms. The rename to method is not reliable: stackoverflow.com/questions/1000183/…
  • Caelum
    Caelum over 8 years
    Path is an interface whose only implementations are WindowsPath, ZipPath and AbstractPath. Will this be a problem for multi-platform implementations?
  • maxivis
    maxivis over 8 years
    Hi @user2104648, here (tutorials.jenkov.com/java-nio/path.html) is an example about how could you handle the files in Linux environment. Basically, you need to use java.nio.file.Paths.get(somePath) instead of using one of the implementations you've mentioned
  • Koray Tugay
    Koray Tugay over 8 years
    What is Path source = ... ?
  • Anh Pham
    Anh Pham over 6 years
    Usually it's better to explain a solution instead of just posting some rows of anonymous code. You can read How do I write a good answer, and also Explaining entirely code-based answers
  • Joel Klinghed
    Joel Klinghed over 6 years
    Copy and rename are usually different operations so I think it should be clearly marked that this is a copy. Which also happens to be unnecessary slow as it copies characters and not bytes.
  • andras
    andras about 5 years
    Only the Path way is working for me, renameTo always returns false. Check either the answer of kr37 or this answer
  • Gaurav
    Gaurav almost 5 years
    @kr37 flawless answer!
  • Forage
    Forage over 4 years
    How is this any different from the accepted answer given by Pierre 9 years earlier?
  • yurin
    yurin about 3 years
    @KorayTugay. Path source = file.getAbsolutePath(); Where file is the file which needs to be renamed.
  • Dmytro Moskovchenko
    Dmytro Moskovchenko over 2 years
    For some reason, the file just disappears if I run it.
  • JohnK
    JohnK about 2 years
    This looks more like making a copy than renaming. What am I missing?