File

Rename file/directory

In this example we shall show you how to rename a File or a directory. To rename a File or a directory one should perform the following steps:

  • Create a new File instance by converting the source pathname string into an abstract pathname.
  • Create a new File instance by converting the target pathname string into an abstract pathname.
  • Use the renameTo(File dest) API method of File to rename the file denoted by the target pathname. Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.io.File;

public class RenameFileDirectory {

	public static void main(String[] args) {

		File file = new File("C://file.txt");

		File newFile = new File("C://new_file.txt");

		// Renames the file denoted by this abstract pathname.
		boolean renamed = file.renameTo(newFile);

		if (renamed) {
			System.out.println("File renamed to " + newFile.getPath());
		}
		else {
			System.out.println("Error renaming file " + file.getPath());
		}
	}
}

 
This was an example of how to rename a File or a directory in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button