Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
151 views
in JAVA by (178k points)
How can I rename a file in Java?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

To rename a file in Java, you can use the File class and its renameTo() method. 

Here's an example:

import java.io.File;

public class RenameFileExample {
    public static void main(String[] args) {
        File oldFile = new File("oldfile.txt");
        File newFile = new File("newfile.txt");
        boolean result = oldFile.renameTo(newFile);
        if (result) {
            System.out.println("File renamed successfully.");
        } else {
            System.out.println("File rename failed.");
        }
    }
}
 

In this example, we create two File objects - one for the old file name ("oldfile.txt") and one for the new file name ("newfile.txt"). We then call the renameTo() method on the old file object, passing in the new file object as an argument. This method returns a boolean value indicating whether the file was successfully renamed or not. We then print a message to the console indicating whether the rename operation was successful or not.

Note that the renameTo() method can also be used to move a file to a different directory by specifying a new path in the File object for the new file name.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Apr 27, 2023 in JAVA by kvdevika (178k points)
0 votes
1 answer
asked Apr 27, 2023 in JAVA by kvdevika (178k points)
0 votes
1 answer
asked Apr 27, 2023 in JAVA by kvdevika (178k points)
0 votes
1 answer
asked Apr 27, 2023 in JAVA by kvdevika (178k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...