Skip to content

Commit 16c762d

Browse files
Merge pull request #79 from HossamSaberr/feature/cls-command
Feat: Implement 'cls' command using native OS calls
2 parents 45acb7b + 1d575f2 commit 16c762d

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

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)