0
votes

so I'd like to know if it's possible to retrieve a key instead of a value from a properties object. I researched it but only came up with examples that list all of the keys. Is there a way to retrieve the key without having to use a loop to filter through all of them to get what I need?

Basically what I have is a login that stores the login info in a properties file where the user name is the key and the value is the password

pass = propertiesObj.getProperty(username);

How would I retrieve the username (the key) from the properties file so I can test if that is the same as what the user entered? I'm just looking for ideas on how to accomplish this, the properties object doesn't have anything to retrieve a key based off a value.

Thanks!

2
A Java [property object ](docs.oracle.com/javase/7/docs/api/java/util/Properties.html) is a hash table. It returns the value with respect to the key ... but you have to iterate through the keys to find a match for any given value. - paulsm4

2 Answers

0
votes

Given the use case you describe I can see no application for retrieving the username from looking it up by password.

The username as entered by the user will not return a password (or rather null) as long as there is not a key with that username. If however the entered username (the key) returns a password which is the same as the password entered by the user, there is a match and you can be sure the key is the same as what the user entered.

Looking up whether a username (key) exists is easy:

 String username = "heresjohnny";
 boolean isValidUsername = props.keySet().contains(username);
0
votes

Properties extends Hashtable. Use the keySet method to get the keys.

If you want to fetch keys for values, then create a new HashMap with the keys and values swapped - by iterating through the keys, pulling out the values and add them to the new HashMap.