Wednesday, March 16, 2016

Java I/O Examples : How To Rename A File or Directory

Intro


This example will demonstrates how to rename a file or directory. To rename a file, you can use File.renameTo() method. This method will return a boolean value. Return true if file is success renamed, and return false if failed to rename.

Examples


package com.freesamplecode.java.io;

import java.io.File;

public class RenameFileDemo {
 public static void main(String[] args){
  
  //create old file object
  File oldFile = new File("D:/test/oldfile.txt");
  
  //create new file object
  File newFile = new File("D:/test/newfile.txt");
  
  //rename old file to new file
  boolean isSuccessfullyRenamed = oldFile.renameTo(newFile);
  
  if(isSuccessfullyRenamed){
   System.out.println("File has been successfully renamed");
  }else{
   System.out.println("Failed to renaming file");
  }
 }
}


Output


File has been successfully renamed

Screenshot

Before rename

How To Rename A File or Directory In Java


After rename

How To Rename A File or Directory In Java

Related Posts:

0 comments: