Created
September 25, 2017 13:32
-
-
Save javamultiplex/35e1c0ed972366120a31f8ee5aba7133 to your computer and use it in GitHub Desktop.
How to rename given file name in Java?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.filehandling; | |
import java.io.File; | |
import java.util.Scanner; | |
/** | |
* | |
* @author Rohit Agarwal | |
* @category File Handling | |
* @problem How to rename given file in Java? | |
*/ | |
public class RenameFile { | |
public static void main(String[] args) { | |
Scanner input = null; | |
try { | |
input = new Scanner(System.in); | |
System.out.println("Enter old file name with extension : "); | |
String oldFileName = input.nextLine(); | |
if (isValidFileName(oldFileName)) { | |
// File is present in current working directory. | |
File oldFile = new File(oldFileName); | |
if (oldFile.exists()) { | |
System.out.println("Enter new file name with extension : "); | |
String newFileName = input.nextLine(); | |
if (isValidFileName(newFileName)) { | |
File newFile = new File(newFileName); | |
oldFile.renameTo(newFile); | |
System.out.println("File renamed successfully."); | |
} | |
} else { | |
System.out.println("Old File doesn't exist in current directory."); | |
} | |
} else { | |
System.out.println("Old file name is not valid."); | |
} | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
private static boolean isValidFileName(String fileName) { | |
// Regular expression for validating file names. | |
String pattern = "^.+\\..+$"; | |
boolean result = false; | |
if (fileName.matches(pattern)) { | |
result = true; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment