在java中禁用echo

时间:2013-06-29 22:17:41

标签: java echo

我试图通过禁用echo来屏蔽密码,但它无效....

通过屏蔽我的意思是输出 * 而不是密码本身....

我查看了控制台的readPassword功能,但它只是禁用了回声。

我是初学者,所以请详细描述......

import java.io.*;
import java.util.*;
//import java.nio.charset.Charset;
//import sun.nio.cs.StreamDecoder;
//import sun.nio.cs.StreamEncoder;
/*class output1 extends OutputStream
{
public void write(int b)
{

}
}
class input1 extends InputStream
{

}*/

class testi
{
static native boolean echo(boolean on) throws IOException;
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//PrintStream out1;
System.out.println("Enter a line: ");
try {
            //cin = new InputStreamReader(System.in);
            //out1=new PrintStream(OutputStream out);
            int c;
            while ((c = br.read()) != -1) {
                //out1.write((int)('*'));
                echo(false);
                System.out.print("*");
            }
            echo(true);
    } finally {
        if (br != null) {
            br.close();
        }
        /*if (out1 != null) {
            out1.close();
        }*/
    }
}
}

这将在控制台(cmd)中运行..

Thanx提前......:)

P.S我在编程上太糟糕了

2 个答案:

答案 0 :(得分:2)

我不确定这是否是您要查找的内容,但即使您在控制台中运行应用,也可以将JOptionPaneJPasswordField一起使用。

以下是http://blogger.ziesemer.com/2007/03/java-password-dialog.html

的示例
final JPasswordField jpf = new JPasswordField();

JOptionPane jop = new JOptionPane(jpf, JOptionPane.QUESTION_MESSAGE,
        JOptionPane.OK_CANCEL_OPTION);

JDialog dialog = jop.createDialog("Password:");
dialog.addComponentListener(new ComponentAdapter() {
    @Override
    public void componentShown(ComponentEvent e) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                jpf.requestFocusInWindow();
            }
        });
    }
});
dialog.setVisible(true);
int result = (Integer) jop.getValue();
dialog.dispose();
char[] password = null;
if (result == JOptionPane.OK_OPTION) {
    password = jpf.getPassword();
}
if (password != null)
    System.out.println("your password: " + new String(password));

答案 1 :(得分:0)

虽然这可能无法解决您正在寻找的方式,但如何将输入隐藏在一起呢?请看下面的链接:

http://www.tutorialspoint.com/java/io/console_readpassword.htm