Tuesday, July 3, 2012

Getting A Line Without Echoing - java.io.Console

Here's a code that can show how to receive a String or a Char[] without echoing




Code:
import java.lang.System;
import java.io.Console;

public class noEcho 

{
public static void main(String[] args) throws Exception 
{
char[] passwd;
Console cons;
if ((cons = System.console()) != null && (passwd = cons.readPassword("[%s]", "Enter Text:")) != null) 
{
String text = new String(passwd);
System.out.println("You Entered :"+text);
}
}
}

Compile: javac noEcho.java
Run: java -cp . noEcho
Sample output:

[Enter Text:]
You Entered :this is a test string

This provision is given Inside a Class called Console and the method to achieive our goal is readPassword() This will receive characters without Echoing.

No comments:

Post a Comment