|
| 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