-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRenameFile.java
50 lines (42 loc) · 1.24 KB
/
RenameFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.javamultiplex.filehandling;
import java.io.File;
import java.util.Scanner;
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 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;
}
}