-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeadCommand.java
More file actions
46 lines (41 loc) · 1.34 KB
/
HeadCommand.java
File metadata and controls
46 lines (41 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package IO;
import java.io.File;
import java.util.Scanner;
public class HeadCommand extends Command {
public HeadCommand() {
super("head");
}
@Override
public void action(String[] cmd) {
int linesToRead = 10; // Default line count
String filePath;
if (cmd.length > 1 && cmd[1].equals("-n")) {
if (cmd.length > 3) {
linesToRead = Integer.parseInt(cmd[2]);
filePath = cmd[3];
} else {
System.out.println("Insufficient arguments. Usage: head -n <n> <file>");
return;
}
} else if (cmd.length > 1) {
filePath = cmd[1];
} else {
System.out.println("Usage: head [-n <n>] <file>");
return;
}
File file = new File(Main.wd, filePath);
if (file.exists()) {
try (Scanner scanner = new Scanner(file)) {
int currentLine = 0;
while (scanner.hasNextLine() && currentLine < linesToRead) {
System.out.println(scanner.nextLine());
currentLine++;
}
} catch (Exception e) {
System.out.println("Error reading file: " + e.getMessage());
}
} else {
System.out.println("File does not exist.");
}
}
}