Rename a file using Java

JavaFileRenameFile Rename

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

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 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

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

    }
}

}

Solution 10 - Java

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.

Solution 11 - Java

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.

Solution 12 - Java

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.

Solution 13 - Java

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

Solution 14 - Java

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.

Solution 15 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShekharView Question on Stackoverflow
Solution 1 - JavaPierreView Answer on Stackoverflow
Solution 2 - Javakr37View Answer on Stackoverflow
Solution 3 - JavaThomas OwensView Answer on Stackoverflow
Solution 4 - JavaZoltánView Answer on Stackoverflow
Solution 5 - JavaBrandonView Answer on Stackoverflow
Solution 6 - JavaseniorView Answer on Stackoverflow
Solution 7 - JavaKirill ChView Answer on Stackoverflow
Solution 8 - JavaanoopknrView Answer on Stackoverflow
Solution 9 - JavaV1ma-8View Answer on Stackoverflow
Solution 10 - JavaDan VintonView Answer on Stackoverflow
Solution 11 - JavaYuvalView Answer on Stackoverflow
Solution 12 - JavaZhurov KonstantinView Answer on Stackoverflow
Solution 13 - JavaTạ Anh TúView Answer on Stackoverflow
Solution 14 - JavarespenicaView Answer on Stackoverflow
Solution 15 - JavaDinesh KumarView Answer on Stackoverflow