216

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?

Jonas Czech
  • 12,018
  • 6
  • 44
  • 65

15 Answers15

211

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*/);
Nathan
  • 8,093
  • 8
  • 50
  • 76
Pierre
  • 34,472
  • 31
  • 113
  • 192
  • 33
    This code won't work in all cases or platforms. The rename to method is not reliable: http://stackoverflow.com/questions/1000183/reliable-file-renameto-alternative-on-windows – Stephane Grenier Oct 21 '09 at 14:49
  • 2
    Only the `Path` way is working for me, `renameTo` always returns false. Check either [the answer of kr37](https://stackoverflow.com/a/20260300/4420543) or [this answer](https://stackoverflow.com/a/13826095/4420543) – andras Jun 09 '19 at 05:52
  • 2
    This looks more like making a copy than renaming. What am I missing? – JohnK May 19 '22 at 13:14
155

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);
Community
  • 1
  • 1
kr37
  • 1,661
  • 1
  • 11
  • 7
  • 3
    Path is an interface whose only implementations are WindowsPath, ZipPath and AbstractPath. Will this be a problem for multi-platform implementations? – Caelum Dec 01 '15 at 15:34
  • 1
    Hi @user2104648, here (http://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 – maxivis Dec 09 '15 at 15:57
  • 3
    What is Path source = ... ? – Koray Tugay Jan 05 '16 at 09:37
  • @kr37 flawless answer! – Gaurav Jul 26 '19 at 15:57
  • @KorayTugay. `Path source = file.getAbsolutePath();` Where `file` is the file which needs to be renamed. – Yuriy N. Apr 16 '21 at 08:14
  • Related re: options supported by `Files.move`, and limitations on what cross-platform guarantees it can provide (like atomically replacing an existing destination file, if renaming within the same filesystem). [How to atomically rename a file in Java, even if the dest file already exists?](https://stackoverflow.com/q/595631) – Peter Cordes Oct 05 '22 at 05:15
32

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.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
31

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.

Zoltán
  • 21,321
  • 14
  • 93
  • 134
19

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();
  }
Brandon
  • 2,034
  • 20
  • 25
17

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");
        }
senior
  • 2,196
  • 6
  • 36
  • 54
5
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);
Kirill Ch
  • 5,496
  • 4
  • 44
  • 65
5

Try This

File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult

Note : We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.

Neuron
  • 5,141
  • 5
  • 38
  • 59
anoopknr
  • 3,177
  • 2
  • 23
  • 33
5

Yes, you can use File.renameTo(). But remember to have the correct path while renaming it to a new file.

import java.util.Arrays;
import java.util.List;

public class FileRenameUtility {
public static void main(String[] a) {
    System.out.println("FileRenameUtility");
    FileRenameUtility renameUtility = new FileRenameUtility();
    renameUtility.fileRename("c:/Temp");
}

private void fileRename(String folder){
    File file = new File(folder);
    System.out.println("Reading this "+file.toString());
    if(file.isDirectory()){
        File[] files = file.listFiles();
        List<File> filelist = Arrays.asList(files);
        filelist.forEach(f->{
           if(!f.isDirectory() && f.getName().startsWith("Old")){
               System.out.println(f.getAbsolutePath());
               String newName = f.getAbsolutePath().replace("Old","New");
               boolean isRenamed = f.renameTo(new File(newName));
               if(isRenamed)
                   System.out.println(String.format("Renamed this file %s to  %s",f.getName(),newName));
               else
                   System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
           }
        });

    }
}

}

V1ma-8
  • 71
  • 1
  • 5
3

If it's just renaming the file, you can use File.renameTo().

In the case where you want to append the contents of the second file to the first, take a look at FileOutputStream with the append constructor option or The same thing for FileWriter. You'll need to read the contents of the file to append and write them out using the output stream/writer.

Dan Vinton
  • 26,401
  • 9
  • 37
  • 79
2

As far as I know, renaming a file will not append its contents to that of an existing file with the target name.

About renaming a file in Java, see the documentation for the renameTo() method in class File.

Yuval
  • 7,987
  • 12
  • 40
  • 54
1
Files.move(file.toPath(), fileNew.toPath()); 

works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with file.renameTo or FileUtils.moveFile.

Matt
  • 1,298
  • 1
  • 12
  • 31
Zhurov Konstantin
  • 712
  • 1
  • 8
  • 14
1

Here is my code to rename multiple files in a folder successfully:

public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
    if(newName == null || newName.equals("")) {
        System.out.println("New name cannot be null or empty");
        return;
    }
    if(extension == null || extension.equals("")) {
        System.out.println("Extension cannot be null or empty");
        return;
    }

    File dir = new File(folderPath);

    int i = 1;
    if (dir.isDirectory()) { // make sure it's a directory
        for (final File f : dir.listFiles()) {
            try {
                File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);

                if(f.renameTo(newfile)){
                    System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
                } else {
                    System.out.println("Rename failed");
                }
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

and run it for an example:

renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");
Tạ Anh Tú
  • 141
  • 1
  • 4
0

I do not like java.io.File.renameTo(...) because sometimes it does not renames the file and you do not know why! It just returns true of false. It does not thrown an exception if it fails.

On the other hand, java.nio.file.Files.move(...) is more useful as it throws an exception when it fails.

-2

Running code is here.

private static void renameFile(File fileName) {

    FileOutputStream fileOutputStream =null;

    BufferedReader br = null;
    FileReader fr = null;

    String newFileName = "yourNewFileName"

    try {
        fileOutputStream = new FileOutputStream(newFileName);

        fr = new FileReader(fileName);
        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            fileOutputStream.write(("\n"+sCurrentLine).getBytes());
        }

        fileOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
            if (br != null)
                br.close();

            if (fr != null)
                fr.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
Anh Pham
  • 2,108
  • 9
  • 18
  • 29
  • 3
    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](https://stackoverflow.com/help/how-to-answer), and also [Explaining entirely code-based answers](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-based-answers) – Anh Pham Sep 23 '17 at 06:43
  • 1
    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. – the_jk Oct 03 '17 at 15:31