The Wayback Machine - https://web.archive.org/web/20240829144154/https://www.geeksforgeeks.org/java-program-to-rename-a-file/
Open In App

Java Program to Rename a File

Last Updated : 09 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Changing the name of the file is known as Renaming the file. Rename operation is possible using renameTo() method belongs to the File class in java.

A. renameTo() Method

The renameTo() method is used to rename the abstract pathname of a file to a given pathname. The method returns a boolean value i.e. returns true if the file is renamed else returns false.

Approach

  1. Create an object of the File class and replace the file path with the path of the directory.
  2. Create another object of the File class and replace the file path with the renaming path of the directory.
  3. Use renameTo() method.
  4. If rename operation successful then the function returns true.
  5. Else returns false.

Below is the implementation of the above approach.

Java




// Java Program to rename a file
import java.io.File;
public class GFG {
    public static void main(String[] args)
    {
        // Create an object of the File class
        // Replace the file path with path of the directory
        File file = new File("/home/mayur/Folder/GFG.java");
  
        // Create an object of the File class
        // Replace the file path with path of the directory
        File rename = new File("/home/mayur/Folder/HelloWorld.java");
  
        // store the return value of renameTo() method in
        // flag
        boolean flag = file.renameTo(rename);
  
        // if renameTo() return true then if block is
        // executed
        if (flag == true) {
            System.out.println("File Successfully Rename");
        }
        // if renameTo() return false then else block is
        // executed
        else {
            System.out.println("Operation Failed");
        }
    }
}


Output:

File Successfully Rename

Before Program Execution

After Program Execution

B. move() Method

Rename of file can be done using move the contents of the first file to a new file and deleting the previous file. Java is handling this operation using resolveSibiling method. It is used to resolve the given path against this path’s parent path

Java




// Java Program to rename a file
import java.nio.file.*;
import java.io.IOException;
  
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
  
        Path oldFile
            = Paths.get("/home/mayur/Folder/GFG.java");
  
        try {
            Files.move(oldFile, oldFile.resolveSibling(
                                    "HelloWorld.java"));
            System.out.println("File Successfully Rename");
        }
        catch (IOException e) {
            System.out.println("operation failed");
        }
    }
}


Output:

File Successfully Rename

Before Program Execution

After Program Execution



Previous Article
Next Article

Similar Reads

How to rename all files of a folder using Java?
Often, when transferring files from the camera folder to a workspace where we would like to analyze the pictures, it becomes difficult to deal with long file and type them out again and again when testing them through a code. Also, the number of files might be too large to manually rename each one of them. Hence, it becomes a necessity to automate
2 min read
Java Program to Read Content From One File and Write it into Another File
File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. Now in order to read conte
5 min read
How to Execute SQL File with Java using File and IO Streams?
In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will learn how to execute an SQL file containing thousand
5 min read
Different Ways to Copy Content From One File to Another File in Java
In Java, we can copy the contents of one file to another file. This can be done by the FileInputStream and FileOutputStream classes. FileInputStream Class It is a byte input stream class which helps in reading the bytes from a file. It provides different methods to read the data from a file. FileInputStream fin = new FileInputStream(filename); This
3 min read
How to Convert a Kotlin Source File to a Java Source File in Android?
We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We'll examine how to convert a Kotlin source file to a Java source file in this blog. Let's get this party started. Because of its interoperability with Java, Kotlin grew at an ex
2 min read
How to Extract File Extension From a File Path String in Java?
In Java, working with Files is common, and knowing how to extract file extensions from file paths is essential for making informed decisions based on file types. In this article, we will explore techniques for doing this efficiently, empowering developers to improve their file-related operations. Program to extract file extension from a file path S
5 min read
How to Create a File with a Specific File Attribute in Java?
In Java, you can create a file with specific File attributes such as read-only, hidden, or system attributes. This allows you to control the behavior and visibility of the file in the File system. In this article, we'll explore how to create a file with specific attributes in Java. In this article, we will learn to create a file with a specific fil
2 min read
Java Program to Extract Content from a Java's .class File
In this article, we are going to extract the contents of the Java class file using the Apache Tika library. Apache Tika is used for document type detection and content extraction from various file formats. It uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing
2 min read
Java program to read all mobile numbers present in given file
Given the input text file, read all mobile numbers present and write to some output file. Suppose we have a file names as input.txt and in that input file we have some Mobile Number which are mixed with some other data. Our task is to read the input file line by line and if we find any Number in that line we have to write that Mobile Number to an a
2 min read
Java Program to Extract Content from a ODF File
The full of ODF is Open Document Format. it is an international family of standards that's the successor of commonly used deprecated vendor-specific document formats like .doc, .wpd, .xls . ODF documents are smaller when compared to other formats. OpenDocumentParser class is used from TIKA library to extract the content from the ODF file. Methods u
3 min read
Java Program to Convert File to a Byte Array
Here, we will go through the different ways to convert file to byte array in Java. Note: Keep a check that prior doing anything first. Create a file on the system repository to deal with our program\writing a program as we will be accessing the same directory through our programs. Methods: Using read(byte[]) method of FileInputStream classUsing Fil
3 min read
Java program to store a Student Information in a File using AWT
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-in
4 min read
Java Program to Change Last Modification Time of a File
Modifying the date of the file is possible through Java using the File class of Java i.e File.setLastModified() method Java File Class The File class is Java’s representation of a file or directory pathname. The File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the cont
3 min read
Java Program to Make a File Read-Only
Read-Only is the file attribute that the operating system assigns to the file. When the file is flagged as read-only, it means that it can only be opened or read, one cannot change the name of the file, can not rewrite or append the content of the file, and also cannot delete the file. Method 1: Using setLastModified Method To make the file read-on
2 min read
Java Program to Search for a File in a Directory
Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java.io.File.list() method. This method
3 min read
Java Program to Create a Temporary File
A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement. Type of File .txt.tmp (Default File Type)Primary, in order to
5 min read
Java Program to Get Last Modification Date of a File
The last modifying date of the file can get through Java using the File class of Java i.e File.LastModified() method. Java File Class The File class is Java’s representation of a file or directory pathname. The File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the conte
3 min read
Java Program to Print all the Strings that Match a Given Pattern from a File
Figure a way out to print all the strings that match a given pattern from a file. To get closer to the goal, concepts of files should be crystal clear so as to think out a way to print strings later on implementing the same to reach the final goal. So prior to dealing with the strings urgency is to discuss out file concepts. Once the file concepts
5 min read
Java Program to Create String from Contents of a File
A File is a computer resource which is deployed to store different types of data such as text, image, video, to name a few. It is basically a collection of data bound to a single entity. While using your computer, it becomes essential to be able to deal with files and in this article we will be learning about various ways to read data from files. W
6 min read
Java Program to Get the File’s Owner Name
The File class is Java’s representation of a file or directory pathname. Because file and directory names have different formats on different platforms, an easy string isn't capable name them. The File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of a direc
3 min read
Java Program to Get the Creation Time of a File
Use java.nio package for extracting the creation date and time of any file through java. To extract the date and time of the file use BasicFileAttributes class. java.nio package helps us to get the creation time, last access time, and last modified time, it works for both file and directory. Approach: Import the necessary java libraries.Store the p
2 min read
Java Program to Read and Print All Files From a Zip File
A zip file is a file where one or more files are compressed together, generally, zip files are ideal for storing large files. Here the zip file will first read and at the same time printing the contents of a zip file using a java program using the java.util.zip.ZipEntry class for marking the zip file and after reading it, the contents inside it wou
4 min read
Java Program to Get the File Extension
The extension of a file is the last part of its name after the period (.). For example, the Java source file extension is “java”, and you will notice that the file name always ends with “.java”. Getting the file extension in Java is done using the File class of Java, i.e., probeContentType() method. The File class is Java’s representation of a file
2 min read
Java Program to Get the Last Access Time of a File
Every file which stores a lot of data, also has its own set of data ( known as metadata) which can be used to get the properties of that file. Such data types are called attributes. Java provides a basis for accessing any attributes of any file such as creation time of the file, last access time, last modified time, type of file, etc. All this can
2 min read
Java Program to Get the Attributes of a File
In Java, there are several packages and API's to perform a lot of different functions. One such package is java.nio.file. This package contains various methods which provide support for files. A package is java.nio.file.attribute, which can be used to access the attributes of the files specified in the path object. So basically we are using the abo
3 min read
Java Program to Find the Most Repeated Word in a Text File
Map and Map.Entry interface will be used as the Map interface maps unique keys to values. A key is an object that is used to retrieve a value at a later date. The Map.Entry interface enables you to work with a map entry. Also, we will use the HashMap class to store items in "key/value” pairs and access them by an index of another type. Illustration
3 min read
Java Program to Get the Basic File Attributes
Basic File Attributes are the attributes that are associated with a file in a file system, these attributes are common to many file systems. In order to get the basic file attributes, we have to use the BasicFileAttributes interface. This interface is introduced in 2007 and is a part of the nio package. The basic file attributes contain some inform
3 min read
Java Program to Read Text From File From a Specified Index
In a file system, without reading the previous text we cannot directly access the specific index. Thus, Reading text from a file from the specific index is achieved by skipping all the previous characters of a specified index. To read text from an index n, we need to skip (n-1) bytes. Here, we will use FileInputStream class to read text from the fi
1 min read
Java Program to Write Data to Temporary File
A Temporary file or a Temp file is a file that is created in order to hold information for some time while a file is being created or modified. After the successful execution of the program or after the program is closed, the temporary file is deleted. Other advantages of having a temporary file are that it helps in storing and moving data, managin
3 min read
How to Create and Modify Properties File Form Java Program in Text and XML Format?
Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article
5 min read