Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ล้างหน้าจอคอนโซลใน Java: Clear Screen

การล้างหน้าจอคอนโซล (Console Clear Screen)

Java ไม่มี API มาตรฐานสำหรับล้างหน้าจอ ต้องใช้ ANSI Escape Codes ซึ่งทำงานได้บนเทอร์มินัลที่รองรับ (Linux/macOS, Windows 10+ Command Prompt/PowerShell)

ตัวอย่างโค้ด

public class Demo { 
    public static void main(String[] args) { 
        // ANSI Escape Code: ESC[H (cursor home) + ESC[2J (clear screen)
        System.out.print("\033[H\033[2J"); 
        System.out.flush(); // บังคับ flush buffer
        
        System.out.println("หน้าจอถูกล้างแล้ว!"); 
    } 
}

คำอธิบาย ANSI Codes

รหัส ESC

  • \033 = Octal escape สำหรับ ESC character (ASCII 27)
  • \u001B = Unicode escape เดียวกัน (อ่านง่ายกว่า)
  • \x1B = Hex escape (ไม่รองรับใน Java string literal)

Cross-Platform Solution

public class ConsoleUtils { 
    public static void clearScreen() { 
        try { 
            String os = System.getProperty("os.name").toLowerCase(); 
            
            if (os.contains("win")) { 
                // Windows: ใช้ cls command
                new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); 
            } else { 
                // Unix/Linux/macOS: ใช้ clear command หรือ ANSI
                System.out.print("\033[H\033[2J"); 
                System.out.flush(); 
            } 
        } catch (Exception e) { 
            // Fallback: พิมพ์บรรทัดว่างเยอะๆ
            for (int i = 0; i < 50; i++) System.out.println(); 
        } 
    } 
}

ข้อจำกัด

  • ANSI codes ไม่ทำงานใน IDE consoles บางตัว (Eclipse เลย, IntelliJ ต้อง enable)
  • Windows เก่า (pre-10) ไม่รองรับ ANSI ต้องใช้ cls command
  • ไม่ใช่ "真正的" clear - scrollback buffer ยังคงอยู่ (เลื่อนขึ้นดูได้)
  • GUI applications (Swing, JavaFX) ไม่ใช้วิธีนี้

ทางเลือกอื่น

  • ใช้ library: JLine, Lanterna, TextTerminal
  • สำหรับ CLI apps จริง ใช้ Picocli หรือ JCommander พร้อม terminal handling
Codeความหมาย
\033[H หรือ \033[1;1HCursor Home - ย้าย cursor ไปมุมบนซ้าย (row 1, col 1)
\033[2JClear Entire Screen - ล้างหน้าจอทั้งหมด
\033[KClear Line - ล้างบรรทัดปัจจุบัน