Java .txt username and password not working [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I was just experimenting with java (NetBeans) and I though up a quick text based adventure game. I'm trying to get it to check for your username and password in two text files "users.txt" and "passwords.txt" and i was following a guide on Cave of Programming
Here are the imports
import java.io.*;
import javax.swing.JFrame;
This is where the errors are,
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
String usernametxt = "users.txt";
String passwordtxt = "passwords.txt";
String user = null;
String pass = null;
try {
// file reader for username \\
FileReader fileReader = new FileReader(usernametxt);
// file reader for password \\
FileReader fr = new FileReader(passwordtxt);
// buffered reader for username \\
BufferedReader bufferedReader = new BufferedReader(fileReader);
// buffered reader for password \\
BufferedReader br = new BufferedReader(fr);
// check for if user doesn't equal null \\
while((user = bufferedReader.readLine()) != null){
// if username equals first line of username.txt \\
if (username.getText().equalsIgnoreCase(user)){
// check for if pass doesn't equal null \\
while((pass = br.readLine()) != null){
// if password equals first line of passwords.txt \\
if (password.getPassword().equals(pass)){
// if password = pass than it will exit \\
System.exit(1);
}
// else continue \\
else{
continue;
}
}
}
}
bufferedReader.close();
br.close();
}
catch(FileNotFoundException ex){
System.out.println("Unable to open file ");
}
catch(IOException ex){
System.out.println("Error reading file");
}
}
Here are the text files
users.txt
matthew
passwords.txt
matt
Full code available here
http://textuploader.com/57urs
Newest Code Here
http://textuploader.com/577qk
feel free to ask me questions here.
Thank you for the help in advance!
Newest Code
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
String usernames = username.getText();
String passwords = password.toString();
boolean signedin = false;
String usernametxt = "users.txt";
String passwordtxt = "passwords.txt";
String user = null;
String pass = null;
try {
FileReader fr1 = new FileReader(usernametxt);
FileReader fr2 = new FileReader(passwordtxt);
BufferedReader br1 = new BufferedReader(fr1);
BufferedReader br2 = new BufferedReader(fr2);
System.out.println("Username: "+br1.readLine());
System.out.println("Password: "+br2.readLine());
// While loops not running (not a if statement error \
while ((user = br1.readLine()) != null){
// checks if username is not equal to usernames.txt \\
if (user.equalsIgnoreCase(usernames)){
System.out.println("while loop running, username (right)");
break;
}
else{
System.out.println("while loop running, username (wrong)");
}
}
br1.close();
while ((pass = br2.readLine())!= null){
if (pass.equalsIgnoreCase(passwords)){
signedin = true;
System.out.println("While loop running, password (right)");
break;
}
else{
System.out.println("While loop running, password (wrong)
}
}
br2.close();
// Commented out the if statements because i dont want to to close while testing \
// if (signedin){
// System.out.println("SIGNEDIN = TRUE");
// new error1().setVisible(true);
// this.dispose();
// }
// if (!signedin){
// System.out.println("SIGNEDIN = FALSE");
// System.exit(1);
// }
}
catch(FileNotFoundException ex){
System.out.println("Unable to open file ");
}
catch(IOException ex){
System.out.println("Error reading file");
}
}
New Problem
The while loops do not run, this is confirmed when it doesn't print "While loop running, User/Pass", This is not a if/then statement error as I have added the else statement to print if the username is right or wrong. Please help, Thanks Matthew.

If i understood it correctly:
Two files:
users.txt holds the usernames.
passwords.txt holds the passwords.
We want:
Keep reading the user file until the file ends or we've found our user.
Read the corresponding line on the password file and check if the password matches.
Checking the code, while((user = bufferedReader.readLine()) != null) does the first part nicely. We DO want to keep reading the entire file trying to find our user, right?
but the nested while seems a bit fishy. We only need to check a SINGLE password for a given user, right? RIGHT?
Digging a bit deeper into your code, we see:
if (password.getPassword().equals(pass)) {
// if password = pass than it will exit
System.exit(1);
} // plus Lots of code...
Hey! I don't think System.exit does what you're looking for!
System.exit will exit the program, going back to DOS or whatever the cool kids are using these days. The integer it returns is called an error code, and can be used to feed info back to the terminal/shell that started our program.
The keyword you're most likely looking for is break: that will exit a given loop pronto, no questions asked.
Let's do some break/continue mashups! Suppose we "Win at life" if the password is indeed correct:
boolean winAtLife = false;
while((user = bufferedReader.readLine()) != null){
String candidatePassword = br.readLine();
if (candidatePassword == null) {
// So the password file is shorter than the userfile?
// We probably want to log or alert the poor DevOp guys.
// throwing an exception seems like the right thing to do here!
break;
}
if (!user.equalsIgnoreCase(username.getText())) {
// These are not the droid we're looking for, Better luck next line!
continue;
// Also notice that, since we KNOW that user can't be null,
// we're using the force to save ourselves from dreaded NullPointerExceptions!
}
if (!candidatePassword.equals(password.getPassword())) {
// Hmmm, wrong password, I guess?
// Not sure what do do next, but we DO NOT need to keep looping
// since we've found our droid/user/whatever.
// So let's break and save some EC2 Cycles.
break;
}
// If we ever reach here, we got ourselves a winner!
pass = candidatePassword
winAtLife = true;
}
EDIT: Ok... So I've heard that:
The cool kids use Scanner nowadays.
Auto-closing resources is good for our health.
Something about separation of concerns and mixing domain-code with the UI. In code samples. Whatever.
So here we go, take two, now as a method:
public boolean checkCredentials(String username, String password) throws IOException {
// these two are begging to be constants or inlined.
final String usernametxt = "users.txt";
final String passwordtxt = "passwords.txt";
if (username == null || password == null) {
// You probably don't want this in production code.
// Exceptions are your best friends when something unexpected occurs.
return false;
}
try (final Reader fileReader = new FileReader(usernametxt);
final Reader passwordReader = new FileReader(passwordtxt)) {
Scanner userScanner = new Scanner(fileReader);
Scanner passwordScanner = new Scanner(passwordReader);
while(userScanner.hasNext()) {
final String user = userScanner.next();
if (!passwordScanner.hasNext()) {
// So the password file is shorter than the userfile?
// We probably want to log or alert the poor DevOp guys.
// throwing an exception seems like the right thing to do here!
return false;
}
final String candidatePassword = passwordScanner.next();
if (!user.equalsIgnoreCase(username)) {
// This is not the droid we're looking for
// Also notice that, since we KNOW that user can't be null,
// we're using the force to save ourselves
// from dreaded NullPointerExceptions!
continue;
}
if (!candidatePassword.equals(password)) {
// Hmmm, wrong password, I guess?
// Not sure what do do next, but we DO NOT need to keep looping
// So let's return early and save some EC2 Cycles.
return false;
}
// If we ever reach here, we got ourselves a winner!
return true;
}
} // yay for autocloseable
return false;
}

Related

in android, trying to find text loaded from an asset file

so what I am trying to accomplish is check a file to see if a word in the file matches the customers input.
I am attaching the code from when the button is clicked and what its supposed to do. Where its failing, or basically not doing it right, is where its supposed to check to see if it is in the list.
*CODE*
btn1.setOnClickListener(new OnClickListener() { // listen for when i click
public void onClick(View v) {
btn1.setText("yeah");
theirpass = edt1.getText().toString().toLowerCase(); // set theirpass = to text boxs input
System.out.println("before i read file theirpass =s "+ theirpass);
System.out.println("before i read file checking =s "+ checking);
readFile(); // read the accouts dude
tv1.setText("i pressed the button");// test to make sure button pressing works
System.out.println("after reading. theirpass =s " + theirpass);
System.out.println("after i read file. checking =s "+ checking);
}// end on click
}); //end listener
}// end oncreate
public void readFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new. InputStreamReader(getAssets().open("account.txt")));
// do reading, usually loop until end of file reading
String mLine = reader.readLine();// reading each line.
while (mLine != null) {
//process line
mLine = reader.readLine();
if. (mLine.matches(theirpass)) { // when an. account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking = theirpass; //trying to set vale of. checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
}// end loop
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
Log.d("Catch buffer","i failed the catch in finally for reading lines");
}
}
}//end buffer reader
Toast.makeText(this,checking,Toast.LENGTH_LONG).show(); //test to get. value of cheking, keeps coming up blank- no text
if (checking == theirpass) {
btn1.setText("its there");//test to see if the if statment works
System.out.println("i just checked if its there");//another test
}
}
}
To help with code
![helping with code again][2]
new Code
if (mLine.equals(theirpass)) { // when an account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking.equals(theirpass); //trying to set vale of checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
mLine = reader.readLine();
} //end buffer reader
value of theirpass
//the value if theirpass is shown below it's in the onClick method
theirpass = edt1.getText().toString().toLowerCase(); // set theirpass = to text boxs input
Try printing the mLine value right after "mLine = reader.readLine();" to know what you read from the file.
But I guess your biggest problem is the misuse of the "matches" function. Matches uses reg ex (http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String) ) .
Instead you should use ".equals" or read this for a good use of string comparison.
You should also change your while loop the this:
// do reading, usually loop until end of file reading
String mLine = reader.readLine();// reading each line.
while (mLine != null) {
//process line
if. (mLine.matches(theirpass)) { // when an. account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking = theirpass; //trying to set vale of. checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
mLine = reader.readLine();
}// end loop
Because you read a line, go into your while, read a new line and have now skipped the first line of the file.

Banning users by reading variable via Java

I am creating a basic password based login system. It uses MD5 to secure the password. The correct password is "csk" (without quotes). If anyone enters that correctly, he gets access to a key.html file in the local computer. But if someone enters the wrong password for three consecutive times, he gets "banned" from logging in again. But the design that I have constructed bans the user only for that particular session. If he opens the terminal again, it starts from the very beginning. If the variable count is greater than 3 (three) from the last time, then the program, on execution via void main() would display "You are banned". I want to keep it basic and not use JDBC and SQL and such. Also, this is a local application and not a web-based one. I'm quite confused what approach I should take on this. Here's my code that I've cooked up:
import java.math.*;
import java.security.*;
import java.io.*;
import java.util.*;
import java.net.HttpURLConnection;
public class pwd {
public static void main(String[] args)throws NoSuchAlgorithmException, IOException, InterruptedException {
int count = 1;
boolean run = true;
while (run && count<4){
System.out.println("Enter the password");
Scanner kb = new Scanner(System.in);
String pass = kb.nextLine();
String pd = "ea0882721f7f44384ce772375696f9a6"; //Password is "csk" without quotes geeks, this is it's MD5
// so enter "csk" in the terminal
// to run the program on execution
String md5sum = md5(pass);
String os = System.getProperty("os.name");
boolean o = false;
int win = os.indexOf("Windows");
if (md5sum.equals(pd)){
System.out.println("You've logged in successfully, get the Key now");
String url = "file:///C:/Users/<username>/Desktop/key.html"; // example www
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
run = false;
}
else {
System.out.println("You've entered the wrong password, try again.");
System.out.println();
run = true;
if (count>=3) {
System.out.println("You are banned from logging in, due to repeated unsuccessful login attempts.");
}
++count;
}
}
}
public static String md5(String input)throws NoSuchAlgorithmException, IOException {
String md5 = null;
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(input.getBytes(), 0, input.length());
md5 = new BigInteger(1, digest.digest()).toString(16);
return md5;
}
}
EDIT: There's no need for me to change MD5 hashing to anything else, it's just a basic one.
you can simply write to a file with java.io.FileWriter
FileWriter writer = null;
String text = "username";
try{
writer = new FileWriter("banned.txt", true);
writer.write("\r\n");
writer.write(text,0,text.length());
}catch(IOException ex){
ex.printStackTrace();
}finally{
if(writer != null){
writer.close();
}
}
The above code allows you to add a line in a file.
To read the file, you can do like this (java.io.BufferedReader):
BufferedReader reader = new BufferedReader(new FileReader("banned.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// check the username here
}
Hum what you want to do can be done but you have to create a kind of "login page" because as it is now (with the code you gave) there is no user information involved.
To save the important information of the ban, you can for example save a boolean in a file (or the user when you have it) and read this same file at the beginning of your code in order to know if user is ban or not. In this case you have to change your code to add the information of ban or not before trying the new input codes ;)
If you don't have a login page, so no user once you ban someone no one will be able to log any more :)
PS: Java class start with a Upper case not pwd but Pwd normally
PS2: Your count will always be increased because it's not in a else ;) so every try of new code will increase it even if the user is ban ;)

Java bufferreader crashes on ctrl z

I'm making a game which plays until the user enters quit in the command line.
The user can enter different commands like get and go, with the get command the user can say what to get like, get baseball bat. What I do in my code is split the command.
everything is working fine but I have found a bug which I can't solve. If I enter "get" and press space and then ctrl+z it gets in a while loop which never ends.
It only happens with ctrl+z (1 time with ctrl c but after that 1 time not anymore)
private void run()
{
while (! quitCommand)
{
String input = null;
try
{
input = null;
System.out.println("Input "+ input);
System.out.println("Give a command.");
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
input = is.readLine();
handleCommand(input);
// As long as the command isn’t to quit:
// get the next input line and handle it. (With handleCommand.)
}
catch (Exception e)
{
System.out.println("Something went wrong we are sorry try again.");
e.printStackTrace();
}
}
}
/**
* #param userInput (This is the entire input string from the user.)
*
* (Tell others to) Perform the task which belongs to the given
* command.
*/
private void handleCommand(String userInput)
{
// Split the user input string.
if (userInput != null) // user input can not be empty
{
String[] delenTekst = userInput.split(" ");
// The first word is a command. The rest is extra information
String command = delenTekst[0];
String extra = "";
for (int i = 1; i < delenTekst.length; i ++)
{
if (i == 1)
{
extra = extra + delenTekst[i];
}
else
{
extra = extra +" " + delenTekst[i];
}
}
switch (command)
{
// Check if the command is to travel between rooms. If so, handle
case "go"
:
this.checkRoomTravel(extra);
break;
// If there isn't any room travel, then check all other command
case "get"
:
System.out.println("Looking for " +extra );
this.handleGetCommand(extra);
break;
case "quit"
:
quitCommand = true;
break;
default
:
System.out.println("Command is not known try help for information");
break;
}
}
else
{
userInput = "help";
}
}
I'm new to java so it can be something really simple.
On the top of my script I have a private boolean quitCommand = false; which is to check if the user entered quit.
Ctrl+Z closes the Console and therefore your readLine() returns null as pretended to indicate that end of file was reached. So all you need to do, is to check for null returned by readLine() and handle this as you handle the "quit".
I've changed your code (just to test my thesis) and also stream lined a few things, e.g. you dont need to recreate a BufferedReader every time you read a line.
private boolean quitCommand = false;
private void runIt() {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while(!quitCommand) {
try {
System.out.print("Give a command: ");
input = is.readLine();
// As long as the command isn’t to quit:
if(input == null || "quit".equals(input.trim())) quitCommand = true;
if(quitCommand) break;
// get the next input line and handle it. (With handleCommand.)
String[] words = input.trim().split("\\s+");
// ** This is the original handleCommand line **
System.out.println(input + ":" + Arrays.toString(words));
}
catch (Exception e) {
System.out.println("Something went wrong we are sorry try again.");
e.printStackTrace();
}
}
}
BTW: To split the input into words I'd use the regular expression as shown in my code. This works also if the user enters tabs or multiple spaces.
On DOS/Windows Ctrl+Z means end of input. This causes readLine() to return null no matter how many times you call it. This is likely to cause your code to fail as you don't appear to check for it. I suspect you are getting a NullPointerException which you are pretending didn't happen and trying again, endlessly.

Pass a string from one class to another in java

I'm trying to pass a String from one class to another class but the result I'm getting is 'null'. I want to pass the String username from LoginFrame to HomeworkFrame;
HomeworkFrame:
public void loadSubjects (){
String item;
try{
System.out.println(username);
Scanner f = new Scanner (new FileReader (username + " " + "Subjects" + ".txt"));
while(f.hasNext()){
item = f.nextLine();
chSubjects.add(item);
}
f.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Subjects cannot be loaded!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
LoginFrame:
public void loginUser(){
r = new Registration();
h = new HomeworkFrame();
l = new Login();
l.username = txtUser.getText();
l.password = txtPass.getText();
try{
String line;
boolean passwordFound = false ;
BufferedReader f = new BufferedReader(new FileReader(l.username + ".txt"));
while((line = f.readLine()) != null){
if(line.equals(l.password)){
passwordFound = true;
}
}
if(passwordFound){
h.username = l.username;
dispose();
m.setSize(700,600);
m.setLocation(100,100);
m.setVisible(true);
}else{
JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
}
f.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Obviously I'm getting the error "Subjects cannot be loaded" as the username is null(I checked it by using the println method).
In case problems like this you have to track your variables/fields from the place you've noticed your 'username' field is null. Next steps should be:
Check what operations you do on 'h' object before you call the loadObjects() method and if any then check what influence they have on username field in HomeWorkFrame (using println or a debugger).
Check if your passwordFound in LoginFrame is true (because if it's false it doesn't assign a value to h.username)
If it's false check if your password's been retrieved from a file (using same println statement)
This kind of scenario should help you finding most of 'null' bugs.
Try to check first, which type of Exception you get.
May be the file is not existing or the list is null or....
Is a format problem : put a \ before your space in pathString : "\ "
You have to write it "\ Subjects.txt", without '+' between.
public class LoginFrame{
private HomeworkFrame hw;
public void doSomething(){
String username = "your username";
hw = new HomeworkFrame(username);
}
}
public class HomeworkFrame{
public HomeworkFrame(String username){
doSomething with 'username'
}
}
Ans to your question! :)
If System.out.println(username); displays null this means that
1.username variable is not initialized and left.
2.value is not assigned to it properly.
3.It might be a static variable and you are changing the value of it.
Please check all these conditions and please give that part of the code from where the loadSubjects() is being called, and not the body of that method as you have provioded it already.
Also all those parts of code where the username is initialized,assigned,modified.
It is required to specify or pass the value otherwise it will definitely give Null as it will not find any value to execute.

Password masking does not terminate the program when needed

I developed the following application in which I needed to masking the PIN and terminate the program after the user has entered the wrong PIN thrice. However, the program terminates only if i close the stopThread at the beginning (I commented it in the code below), however the password masking does not occur for all the three channces when I do so. But, when I close the stopThread just before displaying the login successful screen, the program does not terminate. I need to use ctrl+c to end the program.
Any help is greatly appreciated.
boolean stopThread = false;
boolean hideInput = false;
boolean shortMomentGone = false;
public static double userBal=0.0D;
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 final int NB_OF_TRIES = 3;
public void validatePin(){
BankAccount getAll=new BankAccount();
String pin="";
getAll.Login();
Login hideThread =new Login();
hideThread.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try{
do{
} while(hideThread.shortMomentGone == false );
// Now the hide thread should begin to overwrite any input with "*"
hideThread.hideInput = true; // Read the PIN
System.out.println("\nPIN:");
boolean pinMatch = false;
int i = 0;
while(!pinMatch && i < NB_OF_TRIES) {
hideThread.hideInput = true;
pin = in.readLine();
i++;
//hideThread.stopThread = true; //Program terminates after third attempt
//PIN masking is stopped, if uncommented
System.out.print("\b \b");
if(pin.equals(" ")){
System.out.println("Please do not leave unnecessary spaces!");
getAll.Login();
}else if(pin.equals("")){
System.out.println("Please do not press the enter key without entering the PIN!");
getAll.Login();
}
FileInputStream fileinputstream = new FileInputStream(".\\AccountInfo.txt");
DataInputStream datainputstream = new DataInputStream(fileinputstream);
BufferedReader bufferedreader1 = new BufferedReader(new InputStreamReader(datainputstream));
do
{
String s1;
if((s1 = bufferedreader1.readLine()) == null)
{
break;
}
if(s1.trim().charAt(0) != '#')
{
String as[] = s1.split(" ");
if(pin.equals(as[0]))
{
System.out.println("You have login!");
String s2 = as[2];
userBal = Double.parseDouble(s2);
getAll.balance = userBal;
hideThread.stopThread = true;
getAll.MainMenu();
System.exit(0);
}else if(pin != as[0]){
System.out.println("Invalid PIN!");
getAll.Login();
System.out.println("\n NOTE :- You are only allowed to enter the PIN THREE times. The number of tries remaining before your card is blacklisted are "+i + "\n Please re-enter your PIN");
}
}
} while(true);
datainputstream.close();
}//End of While Loop
}catch(Exception exception)
{
System.err.println((new StringBuilder()).append("Error: ").append(exception.getMessage()).toString());
}//End of try-catch block
}
There's a readPassword() method in java.io.Console, use that. Why do you need a separate thread at all? That makes everything way too complicated.
Regarding your question why this does not close: Java may optimize while(isTrue){} to something like if(isTrue) { while(true) { } } if you don't set isTrue volatile or synchronize the access to isTrue (getter/setter). This optimizations is called hoisting and explained in Effective Java SE, item 66.
Here is an article which explains exactly your problem: echoing * instead of blanks.
http://java.sun.com/developer/technicalArticles/Security/pwordmask/
They are going the complicated way, too but it works. I would prefer blanks over asterisks since that is the easier way to go. Not echoing * is *nix standard afaik.
Actually after I analysed it a but more i realized that the reason the system wont terminate is because it is not kept in the proper place. Therefore, the solution would be to end the program as soon as the while loop is closed and then everything would work fine.
} while(true);
datainputstream.close();
}//End of While Loop
System.exit(0); // After the system is closed the program would terminate after the third attempt
}catch(Exception exception)
{
System.err.println((new StringBuilder()).append("Error: ").append(exception.getMessage()).toString());
}//End of try-catch block

Categories

Resources