×

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

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.