Skip to content

Commit 3537264

Browse files
Refactor ListFilesNIO to LsCommand for shell usage
Refactored ListFilesNIO class into LsCommand implementing Command interface. Added execute, description, and usage methods for shell integration.
1 parent 668544f commit 3537264

1 file changed

Lines changed: 27 additions & 17 deletions

File tree

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,38 @@
1-
import java.nio.file.*;
1+
package com.mycmd.commands;
2+
3+
import com.mycmd.Command;
4+
import com.mycmd.ShellContext;
5+
26
import java.io.IOException;
7+
import java.nio.file.*;
38

49
/**
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.
1711
*/
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();
2117

2218
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
2319
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+
}
2525
}
2626
}
2727
}
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+
}
2838
}

0 commit comments

Comments
 (0)