Hide Password From Command Line

HidePasswordFromCommandLine.java

import java.io.*;

  /**
  * Created on Feb 21, 2003
  */
  public class HidePasswordFromCommandLine extends Thread {
  boolean stopThread= false;
  boolean hideInput= false;
  boolean shortMomentGone= false;
  public void run() {
  try {
  sleep(500);
  } catch (InterruptedException e) {}
  shortMomentGone= true;
  while (!stopThread) {
  if (hideInput) {
  System.out.print("\b*");
  }
  try {
  sleep(1);
  } catch (InterruptedException e) {}
  }
  }
  public static void main(String[] arguments) {
  String name= "";
  String password= "";
  HidePasswordFromCommandLine hideThread= new HidePasswordFromCommandLine();
  hideThread.start();
  BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
  try {
  System.out.println("Name: ");
  // Wait for the username and clear the keyboard buffer (if neccessarry)
  do {
  name= in.readLine();
  }
  while (hideThread.shortMomentGone == false);
  // Now the hide thread should begin to overwrite any input with "*"
  hideThread.hideInput= true;
  // Read the password
  System.out.println("\nPassword:");
  System.out.print(" ");
  password = in.readLine();
  hideThread.stopThread= true;
  }
  catch (Exception e) {}
  System.out.print("\b \b");
  // JUST FOR TESTING - PLEASE DELETE!
  System.out.println("\n\nLogin= " + name);
  System.out.println("Password= " + password);
  }
  }

Related:

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.