คลาส java.io.Console ใช้สำหรับอ่าน/เขียน Console โดยตรง (ไม่ผ่าน Stream) มี readLine() และ readPassword() (ซ่อนอินพุต) ใช้ได้เฉพาะใน Interactive Terminal (ไม่ทำงานใน IDE บางตัว)
การรับ Object Console
Console console = System.console();
if (console == null) {
System.err.println("Console not available (running in IDE?)");
System.exit(1);
}
ตัวอย่างครบถ้วน
import java.io.Console;
import java.io.IOException;
public class ConsoleInputExample {
public static void main(String[] args) throws IOException {
Console console = System.console();
if (console == null) {
System.out.println("Console not supported in this environment.");
return;
}
System.out.print("Enter name: ");
String name = console.readLine();
System.out.print("Enter age: ");
int age = Integer.parseInt(console.readLine());
System.out.print("Enter salary: ");
double salary = Double.parseDouble(console.readLine());
System.out.print("Enter password (hidden): ");
char[] password = console.readPassword(); // Secure!
String pwd = new String(password);
System.out.println("\n--- Summary ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Password length: " + pwd.length());
// Clear password array for security
java.util.Arrays.fill(password, ' ');
}
}
ผลลัพธ์ (ใน Terminal)
Enter name: John Enter age: 30 Enter salary: 50000.50 Enter password (hidden): --- Summary --- Name: John Age: 30 Salary: 50000.5 Password length: 8
Console vs Scanner
| Feature | Console | Scanner |
|---|---|---|
| Read Password (Hidden) | ✅ readPassword() |
❌ |
| Thread-Safe | ✅ | ❌ |
| ทำงานใน IDE | ❌ บางครั้ง (System.console() = null) | ✅ |
| Parsing Built-in | ❌ ต้อง Parse เอง | ✅ nextInt(), nextDouble() |
| Encoding | ใช้ System Default | ระบุได้ |
Best Practice
- ใช้
Consoleสำหรับ Password/CLI Tools ที่รันใน Terminal จริง - ใช้
Scannerสำหรับ General Input/การเรียนรู้/รันใน IDE - Always Check
console != nullก่อนใช้