×

Java Rename File

  • Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible.
  • A file can be renamed using Java's renameTo() function. This method is, however, quite platform-specific; you might be able to properly rename a file under *nix but not in Windows.
  • Therefore, it is always advisable to check the return result to ensure that the file has been successfully renamed (true if successful, false if unsuccessful).
  • The Files.move() method can be used to relocate or rename the empty directory. If the folder is not empty, then a move is permitted if it is possible to transfer the directory without moving the directory's contents.
  • Recursively calling move for the files and subdirectories in a directory would be necessary to transfer the directory and all of its contents. This will be covered in a later article.
  • A built-in class called java.io.File is available in Java for common file operations. This can also be used to rename files.

Rename File Example

  1. Make a "sample.txt" file in the "C:/workspace" directory.
  2. By providing the absolute file location path "C:/workspace/sample.txt," create a File class object.
  3. To rename the file, we must supply a special abstract pathname to the renameTo() method.
  4. The renameTo() method only returns true if the renaming was successful; otherwise, it returns false.
  5. Check the directory to see if the file has been renamed.

Program

import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RenameFile {
 private static final Logger LOGGER = LoggerFactory.getLogger(DeleteFileExample.class);
 public static void main(String[] args) {
renameFile();
 }
 public static void renameFile() {
  File file = new File("C:/workspace/sample.txt");
booleanhasRename = file.renameTo(new File("C:/workspace/sample2.txt"));
  if (hasRename) {
LOGGER.info("File is renamed successfully");
  } else {
LOGGER.info("File reanme failed");
  }
 }
}

There are some other approaches to renaming a file.

  1. ReanameTo() Method
  2. Move() Method

1. RenameTo() Method

A file's abstract pathname can be changed to a specific pathname using the RenameTo() method. If any file is renamed, the procedure returns true; otherwise, it returns false.

Approach

  • Create a File class object and change the file path to the directory location.
  • The file path should be changed to the directory's renaming path in a new object of a File type.
  • RenameTo() should be used.
  • Renaming successfully results in the function returning true.
  • Returns false if Else.

Program

import java.io.File;
public class Demo {
	public static void main(String[] args)
	{
		File file = new File("C:\java\Demo);
		File rename = new File("C:\java\Demo1);
		boolean flag = file.renameTo(rename);
		if (flag == true) {
			System.out.println("File Renamed Successfully ");
		}
		else {
			System.out.println("File Reanme Failed");
		}
	}
}

Output

File Renamed Successfully

2. move() Method

Moving the information from the initial file to the new file as well as deleting the original file can be used to rename a file. Java's resolveSibiling function is being used to handle this action. It is used to compare the given path to the parent path of this path.

Approach

  • Create a File class object and change the file path to the directory location.
  • The file path should be changed to the directory's renaming path in a new object of a File type.
  • RenameTo() should be used.
  • Renaming successfully results in the function returning true.
  • Returns false if Else.

Program

import java.nio.file.*;
import java.io.IOException;
public class Demo {
	public static void main(String[] args)
		throws IOException
	{


		Path oldFile
			= Paths.get("C:\java\program.java");


		try {
			Files.move(oldFile, oldFile.resolveSibling(
									"program1.java"));
			System.out.println("File Renamed Successfully ");
		}
		catch (IOException e) {
			System.out.println(" File Rename failed");
		}
	}
}

Output

File Renamed successfully

Example Programs

Example 1

import java.io.File;
public class Main{
   public static void main(String[] args) {
      File oldName = new File("C:/java/hello.java");
      File newName = new File("C:/java/hi.java");
if(oldName.renameTo(newName)) {
         System.out.println("File renamed successfully");
      } else {
         System.out.println("File rename failed");
      }
   }
}

Output

File Renamed successfully

Example 2

import java.io.File;
public class RenameFileExample { 
   public static void main(String[] args) { 
      File oldfile = new File("C:/java/hello.java"
      File newfile = new File("C:/java/bye.java");
      if(oldfile.renameTo(newfile)) {
System.out.println("File Renamedsuccesful");
      } else {
System.out.println(" File Rename failed");
      } 
   }
}

Output

File Renamed failed

Conclusion

In this article, we looked at various Java file-moving methods. In these code snippets, we concentrated on renaming, but moving is, of course, the same; the only difference is in the target directory.


Related Topics

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.