Skip to content

Commit bb0ab14

Browse files
committed
Feat: Implement 'cls' command using native OS calls
1 parent 45acb7b commit bb0ab14

File tree

2 files changed

+24
-10
lines changed

2 files changed

+24
-10
lines changed

src/main/java/com/mycmd/App.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ private static void registerCommands(Map<String, Command> commands) {
106106
commands.put("unalias", new UnaliasCommand());
107107
commands.put("rename", new RenameCommand());
108108
commands.put("set", new SetCommand());
109+
commands.put("cls", new ClsCommand());
109110
}
110111
}
111112

src/main/java/com/mycmd/commands/ClsCommand.java

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,35 @@
33
import com.mycmd.Command;
44
import com.mycmd.ShellContext;
55

6+
import java.io.IOException;
7+
68
/**
7-
* Clears the console screen by printing multiple blank lines.
8-
*
9-
* This command simulates clearing the terminal screen by outputting 50 blank
10-
* lines, pushing previous content out of view. This is a simple cross-platform
11-
* approach that doesn't rely on terminal-specific control sequences.
12-
*
9+
* Clears the console screen using the native OS command.
10+
*
11+
* This command clears the terminal screen by executing the 'cls' command
12+
* on Windows or the 'clear' command on Unix-like systems (macOS, Linux).
13+
* This provides a true clear-screen functionality.
14+
*
1315
* Usage: cls
14-
*
16+
*
1517
* Note: This command does not accept any arguments.
1618
*/
1719
public class ClsCommand implements Command {
20+
1821
@Override
1922
public void execute(String[] args, ShellContext context) {
20-
for (int i = 0; i < 50; i++) {
21-
System.out.println();
23+
try {
24+
String os = System.getProperty("os.name").toLowerCase();
25+
if (os.contains("win")) { // For Windows Users
26+
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
27+
} else { // For other Operation Systems
28+
new ProcessBuilder("clear").inheritIO().start().waitFor();
29+
}
30+
} catch (InterruptedException e) { // Restore the interrupted status
31+
Thread.currentThread().interrupt();
32+
System.out.println("Error while clearing the screen: " + e.getMessage());
33+
} catch (IOException e) {
34+
System.out.println("Error while clearing the screen: " + e.getMessage());
2235
}
2336
}
24-
}
37+
}

0 commit comments

Comments
 (0)