Home » Core Java » io » File » Rename file/directory

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of