Skip to content

Commit 343f77e

Browse files
Merge pull request #73 from Kaveeshakavindi/feat/Kaveesha/renameCmd
feature: implemented and tested rename command
2 parents 2e3fd89 + c285286 commit 343f77e

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/main/java/com/mycmd/App.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ private static void registerCommands(Map<String, Command> commands) {
103103
commands.put("ipconfig", new IpConfig());
104104
commands.put("alias", new AliasCommand());
105105
commands.put("unalias", new UnaliasCommand());
106+
commands.put("rename", new RenameCommand());
106107
commands.put("tasklist", new TasklistCommand());
107108
}
108109
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.mycmd.commands;
2+
3+
import com.mycmd.Command;
4+
import com.mycmd.ShellContext;
5+
6+
import java.io.File;
7+
import java.io.IOException;
8+
import java.nio.file.Files;
9+
import java.nio.file.StandardCopyOption;
10+
11+
/**
12+
* Implements the "rename" (or "ren") command for MyCMD.
13+
* Usage: rename <oldName> <newName>
14+
*/
15+
public class RenameCommand implements Command {
16+
17+
@Override
18+
public void execute(String[] args, ShellContext context) throws IOException {
19+
if (args.length != 2) {
20+
System.out.println("Usage: " + usage());
21+
return;
22+
}
23+
24+
File oldFile = context.resolvePath(args[0]);
25+
File newFile = context.resolvePath(args[1]);
26+
27+
if (!oldFile.exists()) {
28+
System.out.println("The system cannot find the file specified: " + args[0]);
29+
return;
30+
}
31+
32+
try {
33+
Files.move(oldFile.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
34+
System.out.println("File renamed from " + oldFile.getName() + " to " + newFile.getName());
35+
} catch (IOException e) {
36+
throw new IOException("Failed to rename file: " + e.getMessage(), e);
37+
}
38+
}
39+
40+
@Override
41+
public String description() {
42+
return "Renames a file or directory.";
43+
}
44+
45+
@Override
46+
public String usage() {
47+
return "rename <oldName> <newName>";
48+
}
49+
}

0 commit comments

Comments
 (0)