File tree Expand file tree Collapse file tree 1 file changed +8
-28
lines changed
src/main/java/com/mycmd/commands Expand file tree Collapse file tree 1 file changed +8
-28
lines changed Original file line number Diff line number Diff line change 1- import java .io .File ;
1+ import java .nio .file .*;
2+ import java .io .IOException ;
23
3- public class LsCommand {
4+ public class ListFilesNIO {
5+ public static void main (String [] args ) throws IOException {
6+ Path dir = Paths .get ("." ); // Current directory
47
5- public static void main (String [] args ) {
6- // Determine the directory to list
7- String directoryPath = "." ; // current directory by default
8- if (args .length > 0 ) {
9- directoryPath = args [0 ]; // if user provides a path
10- }
11-
12- File directory = new File (directoryPath );
13-
14- if (!directory .exists ()) {
15- System .out .println ("Directory does not exist: " + directoryPath );
16- return ;
17- }
18-
19- if (!directory .isDirectory ()) {
20- System .out .println (directoryPath + " is not a directory." );
21- return ;
22- }
23-
24- // List files and directories
25- String [] contents = directory .list ();
26- if (contents != null && contents .length > 0 ) {
27- for (String item : contents ) {
28- System .out .println (item );
8+ try (DirectoryStream <Path > stream = Files .newDirectoryStream (dir )) {
9+ for (Path path : stream ) {
10+ System .out .println (Files .isDirectory (path ) ? "[DIR] " + path .getFileName () : " " + path .getFileName ());
2911 }
30- } else {
31- System .out .println ("Directory is empty." );
3212 }
3313 }
3414}
You can’t perform that action at this time.
0 commit comments