Java Files rename and replace extension

Introduction

To rename the file and replace its extension, we can use an explicit name as follows:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

   public static void main(String[] args) throws Exception {
      Path sourceFile = Paths.get("C:/home/docs/users.txt");

      Files.move(sourceFile, sourceFile.resolveSibling("users.bak")); 

   }/* w  w  w  .ja  v  a 2  s.  c o m*/

}
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

   public static void main(String[] args) throws Exception {
      Path sourceFile = Paths.get("C:/home/docs/users.txt");

      String newFileName = sourceFile.getFileName().toString(); 
      newFileName = newFileName.substring(0, newFileName.indexOf('.')) + ".bak"; 
      Files.move(sourceFile, sourceFile.resolveSibling(newFileName)); 

   }//from   www  .  j  a  v a 2 s .c  om

}



PreviousNext

Related