|
1 | | -import java.nio.file.*; |
| 1 | +package com.mycmd.commands; |
| 2 | + |
| 3 | +import com.mycmd.Command; |
| 4 | +import com.mycmd.ShellContext; |
| 5 | + |
2 | 6 | import java.io.IOException; |
| 7 | +import java.nio.file.*; |
3 | 8 |
|
4 | 9 | /** |
5 | | - * Lists files and directories using Java NIO (New I/O) API. |
6 | | - * |
7 | | - * This is a standalone utility class that demonstrates directory listing |
8 | | - * using the modern java.nio.file package. It lists all entries in the |
9 | | - * current directory, marking directories with [DIR] prefix and files with |
10 | | - * spacing for alignment. |
11 | | - * |
12 | | - * Usage: java ListFilesNIO |
13 | | - * |
14 | | - * Note: This class has a main method and can be run independently. It uses |
15 | | - * DirectoryStream for efficient directory traversal and automatically closes |
16 | | - * resources using try-with-resources. |
| 10 | + * LsCommand - lists files and directories in the shell's current directory. |
17 | 11 | */ |
18 | | -public class ListFilesNIO { |
19 | | - public static void main(String[] args) throws IOException { |
20 | | - Path dir = Paths.get("."); // Current directory |
| 12 | +public class LsCommand implements Command { |
| 13 | + |
| 14 | + @Override |
| 15 | + public void execute(String[] args, ShellContext context) throws IOException { |
| 16 | + Path dir = context.getCurrentDir().toPath(); |
21 | 17 |
|
22 | 18 | try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { |
23 | 19 | for (Path path : stream) { |
24 | | - System.out.println(Files.isDirectory(path) ? "[DIR] " + path.getFileName() : " " + path.getFileName()); |
| 20 | + if (Files.isDirectory(path)) { |
| 21 | + System.out.println("[DIR] " + path.getFileName()); |
| 22 | + } else { |
| 23 | + System.out.println(" " + path.getFileName()); |
| 24 | + } |
25 | 25 | } |
26 | 26 | } |
27 | 27 | } |
| 28 | + |
| 29 | + @Override |
| 30 | + public String description() { |
| 31 | + return "List files and directories in the current directory."; |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public String usage() { |
| 36 | + return "ls"; |
| 37 | + } |
28 | 38 | } |
0 commit comments