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 4 years ago.
Improve this question
so, let's say that i have this code
String some = ("my name|username|password");
String[] split = some.split("|");
i want to have a string like this
split[0] = "my name";
split[1] = "username";
split[0] = "password";
here is my code
String record = null;
FileReader in = null;
MainMenu menu = null;
public void checkLogin() throws FileNotFoundException, IOException, ArrayIndexOutOfBoundsException {
in = new FileReader("D:\\Login.txt");
BufferedReader br = new BufferedReader(in);
String username = txfUsername.getText();
String password = new String(txfPassword.getPassword());
while ((record = br.readLine()) != null) {
String[] split = record.split("-");
if (username.equals(split[1]) && password.equals(split[2])) {
JFrame frame = new JFrame();
menu = new MainMenu(split[0]);
this.setVisible(false);
menu.setVisible(true);
break;
}
}
if (menu == null) {
JOptionPane.showMessageDialog(null, "Username or Password wrong.");
}
}
and here is login.txt
my name-user-pass
when i run the program it will throw arrayindexoutofbound exception
how to get rid of that?
In my opinion, when dealing with a text file you want to always make sure you are actually processing a data line especially if your app is not responsible for creating the text file. You should also always be aware of the fact that the data line may not contain all the required data so as to eliminate the possibility of encountering a ArrayIndexOutOfBoundsException when utilizing the String.split() method.
You may also want to allow for a mechanism to handle comment lines within the text file so that some can be added. These lines would of course be ignored as would blank lines. In this case the text file path and file name is hard coded within the method but if the file was to be User selectable via a JFileChooser (or whatever) it would be good if the very first line of the file was a comment line indicating what the file is for, for example:
;MyAppName Login Data
;Real Name, Login Name, Password
John Doe, johnnyboy, cGFzczEyMzQ
Bill Smith, BoperBill, U3VwZXJDb29sMQ
Tracey Johnson, tracey, NzcyMzQ2Ng
Fred Flinstone, PebblesDaddy, V2lsbWEnc19EdWRl
In the example file layout above, lines that start with a semi-colon (;) are considered comment lines. The very first comment is the File Descriptor. When the file is read then this line is checked and if it states what is expected then you know for a fact that it is most likely a correct text file to process otherwise the User supplied or selected a wrong text file.
You will notice that the passwords are encrypted. Not even you should know what they are. Passwords are private to the User only. A simple Base64 Encryption is used here (Java 8+ required) but only for example purposes. It may be good enough for a some applications but definitely not for all, but still, something is better than nothing at all.
To encrypt a password in Base64 in your case you might use (import java.util.Base64 required):
String password = Base64.getEncoder().withoutPadding().
encodeToString(String.valueOf(txfPassword.
getPassword()).getBytes());
Do this before saving the User Password to file.
Here is how your checkLogin() method might look:
public void checkLogin() throws FileNotFoundException, IOException {
// Try with Resources...This will auto-close the BufferReader.
try (BufferedReader br = new BufferedReader(new FileReader("D:\\Login.txt"))) {
// Install code here to validate that txfUsername and txfPassword
// text boxes actually contain something. Exit method if not.
// ................................
String userName = txfUsername.getText();
// Encrypt supplied password and compare to what is in file
String password = Base64.getEncoder().withoutPadding().encodeToString(String.valueOf(txfPassword.getPassword()).getBytes());
if (userName.equals("") || password.equals("")) {
return;
}
String line;
int lineCounter = 0;
boolean loginSuccess = false;
while ((line = br.readLine().trim()) != null) {
lineCounter++;
// Is this the right data file?
if (lineCounter == 1 && !line.equals(";MyAppName Login Data")) {
JOptionPane.showMessageDialog(this, "Wrong Text File Supplied!",
"Invalid Data File", JOptionPane.WARNING_MESSAGE);
return;
}
// Skip blank and comment lines...
if (line.equals("") || line.startsWith(";")) { continue; }
// Split the comma/space delimited data line (", ")
String[] lineSplit = line.split(",\\s+"); // \\s+ means 1 or more spaces
// make sure we have three array elements
if (lineSplit.length == 3 && userName.equals(lineSplit[1]) && password.equals(lineSplit[2])) {
loginSuccess = true;
JFrame frame = new JFrame();
menu = new MainMenu(lineSplit[0]);
this.setVisible(false);
menu.setVisible(true);
break;
}
}
// Can't find login name or password in file.
if (!loginSuccess) {
JOptionPane.showMessageDialog(this, "Invalid User Name or Password!",
"Invalid Login", JOptionPane.WARNING_MESSAGE);
}
}
}
Related
I have a GUI for user login.
First the user creates his account, and that information is stored in a .txt file. I use PrintWriter to append details in that file.
The details are stored using a separator. I can easily read every detail of a user from the file.
In the login UI, I have 2 JTtextField components in a JFrame the first one for the user name and the second onw for the password.
I get the values using the getText method:
String user = user.getText();
String password = password.getText();
I tried using BufferedReader but I can't get it to work:
if(user.equals(br.readline))
What i want to do is scan the file and if anything in the file is equal to the username (The getText from user on Frame) then I want to use SetVisible to go to Next Frame
My problem is that even on wrong password and user it go to new frame
How can I fix that?
Code to Check for User and Password, found online on StackOverflow still now working.
Scanner sc = new Scanner(new File("Details.txt"));
while(sc.hasNextLine()) {
int val =0;
String line = sc.nextLine();
if(line.indexOf(user) !=-1 && line.indexOf(pass) !=-1) {
JOptionPane.showMessageDialog(null,"Login");
val = 1;
vf.setVisible(true);
break;
} else {
JOptionPane.showMessageDialog(null,"Invalid");
val = 0;
break;
}
}
Another Code which is used in for , while even in do while loop , still not working.
File file = new File("Details.txt");
BufferedReader br = new BufferedReader(new FileReader("Details.txt"));
String Line;
do{
if(user.equals(br.readLine()) && pass.equals(br.readLine())){
vf.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,"Invalid");
}
}while((Line=br.readLine()) !=null )
This is how Users Details are Stored in My File.
=======================
=======================
First Name = Ahmed Ali
Last Name = Qazi
Address = Al-Abbass Colony pHase 2
Phone Number = +92032329301
Email Address = ahmedrider56#gmail.com
UserName = ahmedfirst67
Password = dangerd = 2hg
=======================
=======================
=======================
=======================
First Name = Ahm345
Last Name = Qa345
Address = Al-asfafs
Phone Number = +92032329301
Email Address = ahmgsdg
UserName = ahmegg
Password = dagg
It is not straightforward given your file structure but you can do it this way:
Scan the file until you find the username.
Once you found the user name, keep scanning until you reach the password line.
Read this password and exit the scanning loop.
Then compare the given password with the one you found in the file.
Here is the code:
private static boolean checkCredentials(String user, String pass) throws IOException {
Scanner sc = new Scanner(new File("Details.txt"));
boolean userFound = false;
String correctPassword = null;
String line;
while(sc.hasNextLine()) {
line = sc.nextLine();
// find the user
if(!userFound) {
userFound = line.contains("UserName = "+user);
} else {
// find the password
if(line.contains("Password = ")) {
correctPassword = line.substring(line.indexOf("=") + 2);
break;
}
}
}
return correctPassword!=null && correctPassword.equals(pass);
}
public static void main(String[] args) throws IOException {
System.out.println(checkCredentials("Bob", "dagg"));
System.out.println(checkCredentials("ahmegg", "daggy"));
System.out.println(checkCredentials("ahmegg", "dagg"));
}
This prints:
false
false
true
Stick it in your code like this:
val = 0;
String message = "Invalid";
if(checkCredentials(user, pass)) {
message = "Login";
val = 1;
vf.setVisible(true);
}
JOptionPane.showMessageDialog(null, message);
NOTE:
It would be lot easier if you stored the details on one line this way:
Ahmed Ali|Qazi|Al-Abbass Colony pHase 2|+92032329301|ahmedrider56#gmail.com|ahmedfirst67|dangerd = 2hg
Ahm345|Qa345|Al-asfafs|+92032329301|ahmgsdg|ahmegg|dagg
You could use the String.split method to parse each line and get user and password at the same time.
NOTE 2:
Also it is very bad practice to store password unencrypted. If this is a school exercise it is fine, but if it is for a real life project, you might want to look at encrypting the passwords in the file.
Cannot understand why following code doesn't work properly. Firstly, system getting input from the user. Then system reads all data from .txt file and compare with the user input. But the system never finds similar username and password.
The idea is to create simple login that based on the stored username and password in .txt file. Could someone help?
private static void login() {
String record = null;
FileReader in = null;
try {
in = new FileReader("adminlogin.txt");
BufferedReader br = new BufferedReader(in);
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String user = keyboard.nextLine();
System.out.print("Password: ");
String pass = keyboard.nextLine();
while ((record = br.readLine()) !=null) {
if (user.equals(record) && pass.equals(record)) {
Mainemenu menu = new Mainemenu();
menu.AdminMenu();
} else {
System.out.println("________----Error----________\n press 'Enter' to continue...");
keyboard.nextLine();
checkInput();
}
}
} catch (IOException e) {
e.getCause();
}
}
Your problem is the loop and its comparison:
while ((record = br.readLine()) !=null) {
if (user.equals(record) && pass.equals(record)) {
//...
}
//...
}
You read a whole line from your file, which is in record, but then you compare both user and pass with this line. This will never work, except user is equal to pass.
Either you have stored the user name and password in a line in your file - then you have to split the line into user name and password - or you have the name and password stored in two separate lines - then you need to reads in the loop for each user.
Moreover, you do throw an error after you checked only the first user and you do not exit the loop, if you actually found the user.
Solutions
I suppose your records in the file are like "username password", then do:
Mainemenu menu = null;
while ((record = br.readLine()) !=null) {
// Split line by a whitespace character
// split[0] <- username
// split[1] <- password
String[] split = record.split("\\s");
if (user.equals(split[0]) && pass.equals(split[1])) {
menu = new Mainemenu();
menu.AdminMenu();
// You found the user, exit the loop
break;
}
// Delete else branch
}
if (menu == null) {
// User not found
}
Of course you can use any other delimiter character or sequence for your records by adopting the delimiter string in split.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my program, I am asking users for input for a subject name and a subject code which i pass through to a subjects.txt file eg:
Inside the TestSubject class -
//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();
//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();
//add records to the file
subject.addRecords(subjectName, subjectCode);
Inside the subject class -
//add the records of valid subject name and subject code
public void addRecords(String name, String code) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
out.printf(name);
out.printf("\n");
out.printf(code);
out.printf("\n");
out.close();
}catch (IOException e) {
}
}
I then want to read this file and pass the data through to an arraylist. The file might look something like:
Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789
I want to pass it through to an arraylist so then I can then process other methods against this array such as sorting, see if any are the same etc.
//read data from subjects file and place in an array
public void readData(){
Scanner input = new Scanner("subjects.txt");
while (input.hasNext()) {
String subjectName = input.nextLine();
String subjectCode = input.nextLine();
}
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//add the input to the arrays
subjectNames.add(subjectName);
subjectNames.add(subjectCode);
//display the contents of the array
System.out.println(subjectNames.toString());
System.out.println(subjectCodes.toString());
}
Even if there is a good tutorial around that I might be able to be pointed in the right direction...
Thanks for editing your post. Much easier to help when I can see what's causing problems.
You're checking hasNext() once every two lines. Should be checked every line because you shouldn't trust the text file to be what you expect and should display an informative error message when it isn't.
You're also declaring the strings inside the scope of the loop so nothing outside the loop even knows what they are. Shoving subjectCode into into the subjectNames collection is probably not what you want. As it is, each nextline() is stepping on the last string value. That means you're forgetting all the work done in previous iterations of the loop.
The collections.add() calls, not the strings, should be in the loop. Make sure to declare the collections before the loop and put their add calls in the loop. See if you get useful results.
Give "Reading a plain text file in Java" a read.
Regarding your tutorial query, I often find some good basic examples on this site including one for reading from a file as referenced in the link. Using the main principles of that example here is one way you could try and read the lines from your file:
public static void main(String[] args){
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//Path leading to the text file
Path data = Paths.get(System.getProperty("user.home"), "Desktop", "file.txt");
int count = 0;//Will indicate which list to add the current line to
//Create a buffered reader to read in the lines of the file
try(BufferedReader reader = new BufferedReader(new FileReader(data.toFile()))){
String line = "";
while((line = reader.readLine()) != null){//This statement reads each line until null indicating end of file
count++;//Increment number changing from odd to even or vice versa
if(count % 2 == 0){//If number is even then add to subject codes
subjectCodes.add(line);
} else {//Otherwise add to subject names
subjectNames.add(line);
}
}
} catch (IOException io){
System.out.println("IO Error: " + io.getMessage());
}
System.out.println("Codes: ");
display(subjectCodes);
System.out.println("\nNames: ");
display(subjectNames);
}
private static void display(Collection<String> c){
for(String s :c){
System.out.println(s);
}
Hope it helps!
I want help myself, I made a file that would create a user file, because I plan on making a game. It has a login that writes the Login name, the Display name, and the Password. It writes it out to a file named after the Login Name.
Now I wish to make a login script as well, using java. I want to know, specifically, how to read the line and the already entered password.
I have it so that when it creates the file, it saves the password twice, once as "playerPass" and once as "currPass" so that, if one planned to change the password (which I will use from the login script), then the currPass would be read as the correct password using the playerPass variable. Anyway, I would like for it to use BufferedReader and FileReader to read the line indicating the password and the current password so that one may log in.
Can someone help me out a lot with this? I am still, to a point, novice.
PS. I can tweak code, I just need a little explanation on HOW TO code it lol.
Variables:
playerLogName
playerName
playerPass
currPass
File names:
Login.java
CharacterFileCreator.java
MADE AN ADDITION, got it half working, but it locks up (using Dr. Java) after I enter password, regardless of what I do, incorrect or correct, and the System.out.println() never executes, even if the password is incorrect. Check it:
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
class Login {
public static void LogIn(){
boolean loggedIn = false;
loggedIn = true;
System.out.println("You are now logged in!");
}
public static void main(String[] args) {
System.out.println("What is your login name?");
Scanner charLogName = new Scanner(System.in);
String playerLogName = charLogName.nextLine();
boolean charFileFound = false;
BufferedReader characterfile = null;
try {
characterfile = new BufferedReader(new FileReader("./game/characters/" + playerLogName + ".txt"));
charFileFound = true;
}
catch (FileNotFoundException fileex1) {}
if(charFileFound == false){
System.out.println("Login name does not exist!");
}
else
{
System.out.println(playerLogName + ": is your username, what is your password?");
Scanner charPassword = new Scanner(System.in);
String playerPass = charPassword.nextLine();
String line = "";
String token = "";
String token2 = "";
int ReadMode = 0;
try {
line = characterfile.readLine();
} catch (IOException ioexception) {
System.out.println(playerLogName + ": error loading file.");
}
while (line != null) {
line = line.trim();
int spot = line.indexOf("=");
if (spot > -1) {
token = line.substring(0, spot);
token = token.trim();
token2 = line.substring(spot + 1);
token2 = token2.trim();
switch (ReadMode) {
case 1:
if (token.equals("character-password")) {
if (playerPass.equals(token2)) {
LogIn();
} else {
System.out.println("You entered an incorrect password!");
}
break;
}
}
} else {
if(line.equals("[ACCOUNT]")) {
ReadMode = 1;
}
else if(line.equals("[EOF]")) {
try {
characterfile.close();
} catch (IOException ioexception) {
}
}
}
}
}
}
}
EDIT:
SAMPLE FILE:
[ACCOUNT]
character-loginname = SampleFile
character-password = samplepassword
[EOF]
It would probably be easier to use a properties file! You can still give it any file extension you want and even encrypt it if you so wish, but by using the Properties object you can get or set any property regardless of the line number!
Look here for an example: http://www.exampledepot.com/egs/java.util/Props.html
UPDATE: I have spotted your problem - you are never reading the next line of the file in your while loop, so you would probably find that if you put System.out.println(line); somewhere inside of the loop it would just keep displaying "[ACCOUNT]" - the first line of your file!
To solve this problem, I may be inclined to put the entire loop in a try catch statement and change the condition to while((line = characterfile.readLine()) != null). That way, every loop uses the next line, but it could be problematic in terms of catching exceptions, depending on the situation.
Alternatively, you could add line = characterfile.readLine(); after you set ReadMode to 1 in your if(line.equals("[ACCOUNT]")) statement, and as an else statement when testing if (token.equals("character-password"))....
However, if you do follow my advice and use the Properties file you will not be required to do any looping to get the character data as you can just call something like password = propertyObject.getyProperty("password") as the example link shows.
HTH
I have a very big text file with customer information. I would like to read all the customer information from the text file.
This is how my text file is organized:
Costomer 1:
Name:
Erik Andersson
Adress:
Street1
Phone number:
085610540
Costomer 2:
Name:
Lars Larsson
Adress:
Street1
Phone number:
085610540
I would like to be able read all the customer information. Is there any good way to it with? I have read about Scanner and Pattern and was wondering if it is good idea to use them in this case? My text file is very big and contains hundreds of customers.
Dose any one have any idea how I could read all the information from the text file? I have created a class with customer variabled, I only need help with the reading from the text file. I want to read the information in an organized way.
All help is very very appreciated.
Like so:
public void getEmployees(File f) throws Exception {
// An ArrayList of your Employee-Object to hold multiple Employees
ArrayList<Employee> employees = new ArrayList<Employee>();
// The reader to read from your File
BufferedReader in = new BufferedReader(new FileReader(f.getAbsolutePath()));
// This will later contain one single line from your file
String line = "";
// Temporary fields for the constructor of your Employee-class
int number;
String name;
String adress;
String phone;
// Read the File untill the end is reached (when "readLine()" returns "null")
// the "line"-String contains one single line from your file.
while ( (line = in.readLine()) != null ) {
// See if your Line contains the Customers ID:
if (line.startsWith("Customer")) {
// Parse the number to an "int" because the read value
// is a String.
number = Integer.parseInt(s.substring("Customer ".length()).substring(0,s.indexOf(':')));
} else if (line.startsWith("Adress:")) {
// The Adress is noted in the next line, so we
// read the next line:
adress = in.readLine();
} else if (line.startsWith("Phone number:")) {
// Same as the Adress:
phone = in.readLine();
} else if (line.startsWith("Name:")){
// Same as the Adress:
name = in.readLine();
} else if ( line.equals("") ){
// The empty line marks the end of one set of Data
// Now we can create your Employee-Object with the
// read values:
employees.add(new Employee(number,name,adress,phone));
}
}
// After we processed the whole file, we return the Employee-Array
Employee[] emplyeeArray = (Employee[])employees.toArray();
}
Please give +1 and correct for ur hw lol
As a little extension to stas answer:
The originally posted code doesn't work, because a continue skips the current loop-iteration. So unless the line starts with "", nothing is ever done.