How to rename file in Java?

The following example explain how to rename file in Java with java.io.File.renameTo(File dest), this method is really platform-dependent.

package com.nourit.javaIO;

import java.io.File;

public class RenameFile {

  public static void main(String[] args) {
    File newfile =new File("D:/tmp/nourit.txt");
    File oldfile =new File("D:/tmp/nourit-new.txt");

    if(oldfile.renameTo(newfile)){
      System.out.println("Rename succesful: " + newfile.getName());
    }else{
      System.out.println("Rename failed");
    }
  }
}

Output:

Rename succesful: nourit-new.txt

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*