Skip to content

Commit cd738eb

Browse files
Merge branch 'main' into ItTakesNothing
2 parents 8bca22d + c1496b2 commit cd738eb

File tree

1 file changed

+8
-28
lines changed

1 file changed

+8
-28
lines changed
Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,14 @@
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
}

0 commit comments

Comments
 (0)