java.io.Console क्लास कंसोल से इनपुट पढ़ने के लिए readLine() और readPassword() प्रदान करती है। यह IDEs (गैर-इंटरैक्टिव वातावरण) में काम नहीं कर सकती।
उदाहरण
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 available (running in IDE?)");
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 password: ");
char[] pwd = console.readPassword(); // सुरक्षित पासवर्ड इनपुट
System.out.println("Password length: " + pwd.length);
System.out.println("Name: " + name + ", Age: " + age);
}
}आउटपुट (कमांड लाइन)
Enter name: Krishna Enter age: 26 Enter password: Password length: 5 Name: Krishna, Age: 26
मुख्य बिंदु
System.console()null लौटाता है यदि कंसोल उपलब्ध नहीं है (उदाहरण: Eclipse, IntelliJ)।readPassword()char[]लौटाता है (स्ट्रिंग से अधिक सुरक्षित)।- IDE में,
ScannerयाBufferedReaderका उपयोग करें।