I have a properties file that holds username and password which I use in my java program however I am not being able to store more than one username and password like I do in database and just select where username and password match the many rows in the database. I imagine I need to have a two-dimensional array stored in the file holding usernames and corresponding passwords but I've failed to figure out how to do it and neither has google given me a way to hold a two-dimensional array in a file yet. Here are the key/value pairs for my username and password in the file
`password=k
username=k`
And here is the code that reads them and compares with what the user inserts
`String usr = userfield.getText();
String pwd = new String(pwdfield.getPassword());
Properties config = new Properties();
InputStream is;
try {
is = new FileInputStream("config.properties");
config.load(is);
if (usr.toString().equals(config.getProperty("user").toString()) && pwd.toString().equals(config.getProperty("pass").toString())) {
new DocMenu();
lgFrame.dispose();
} else {
JOptionPane.showMessageDialog(lgFrame, "Wrong credentials try again", "Oops", JOptionPane.ERROR_MESSAGE);
}
is.close();
} catch (Exception ex) {
System.out.println(ex);
ex.printStackTrace();
}`
Could someone please tell me how to change the properties file and the code so that I am able to have multiple usernames and passwords in the file to grant access to any user as long as their username and password exist.
If you store the property name as a concatenation of some key with the username, and the password as the value like this;
#Some bad passwords
username.bob=password
username.scott=tiger
username.admin=admin
..then you can check like this;
String password = config.getProperty("username." + usr.toString());
if (password != null && password.equals(pwd.toString())) {
new DocMenu();
lgFrame.dispose();
} else {
JOptionPane.showMessageDialog(lgFrame, "Wrong credentials try again", "Oops", JOptionPane.ERROR_MESSAGE);
}
In your posted code, you have 'username' in the properties, and you are trying to read the 'user' property.
Same goes for the password.
But this will only allow you yo have one pair user/pwd. You should have a more elaborated structure in your properties file. For instance you could have
user1=pwd1
user2=pwd2
...
and then check with something like :
if (password != null && password.equals(config.getProperty(usr)){
// ok ...
}
If you have to use properties, I think there's little option beyond doing
username.1
username.2
username.3
and iterating through until you have an index that you can't find the property for (in this case, username.4).
For more complex configurations, I would investigate frameworks such as Apache Commons Config, which can handle lists of elements.
As promised, here is the HashSet serialise/deserialise code:
import java.util.*;
import java.io.*;
class UserPasswordMap{
private HashMap<String,String> userMap;
private String m_filename;
public UserPasswordMap()
{
userMap = null;
m_filename = null;
userMap = new HashMap<String,String>();
}
public UserPasswordMap(String filename, String credo)
{
try{
m_filename = filename;
File f = new File(m_filename);
userMap = new HashMap<String,String>();
if(f.exists() && (!(f.canRead() && f.canWrite()))){
System.err.println("Oops, Insufficient permissions to read/write for filename: "+m_filename);
}else{
f.createNewFile();
}
}catch(Exception e){
System.err.println(e.getMessage());
}
if(credo.equals("D")){
try{
ReadMap(filename);
}catch(Exception e){ System.err.println(e.getMessage());}
}
}
public void ReadMap(String filename) throws IOException, ClassNotFoundException
{
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
userMap = (HashMap<String,String>)ois.readObject();
fis.close();
}
public void WriteMap(String filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userMap);
oos.close();
}
public ArrayList<String> getUsers()
{
ArrayList<String> users = new ArrayList<String>();
if(userMap == null){
return null;/*or return users*/
}else{
for(String s:userMap.keySet()){
users.add(s);
}
}
return users;
}
public ArrayList<String> getPasswords()
{
ArrayList<String> passwords = new ArrayList<String>();
if(userMap == null){
return null;/*or return users*/
}else{
for(String s:userMap.values()){
passwords.add(s);
}
}
return passwords;
}
public String getPassword(String username)
{
return userMap.get(username);
}
public void addUser(String username, String password){
userMap.put(username, password);
try{
WriteMap(m_filename);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
public void saveData(){
if(m_filename == null){
System.err.println("File-Name is not supplied");
}else{
try{
WriteMap(m_filename);
}catch(Exception e){
System.err.println(e.getMessage());
}
}
}
}
And the test code:
public class Main{
private UserPasswordMap map;
public static void main(String[] args){
Main obj = new Main();
obj.init();
Scanner scan = new Scanner(System.in);
System.out.println("0. Init With Serialisation(CAN THROW ERROR)");
while(true){
System.out.println("1. Add New User");
System.out.println("2. Query Permissions");
System.out.println("3. Exit");
int data = scan.nextInt();
switch(data){
case 0: obj.initWithSerialisation();
break;
case 1: obj.addNewUser();
break;
case 2: obj.queryPerms();
break;
case 3: System.exit(0);
}
}
}
public void init()
{
map = new UserPasswordMap("try1.ser","");
}
public void initWithSerialisation()
{
map = new UserPasswordMap("try1.ser","D");
}
private Scanner scan;
public void addNewUser()
{
System.out.print("Enter User:");
scan = new Scanner(System.in);
String username = scan.nextLine();
System.out.print("Enter Pass:");
String password = scan.nextLine();
map.addUser(username, password);
}
public void queryPerms()
{
System.out.print("Enter User:");
if(scan == null){ scan = new Scanner(System.in);}
String username = scan.nextLine();
System.out.print("Enter Pass:");
String pass = scan.nextLine();
if(map.getUsers().contains(username) && map.getPassword(username).equals(pass)){
System.out.println("authenticated!");
}else{
System.out.println("Oops Wrong credentials!");
}
}
}
Related
i have a problem in my java exercise.
i need to print a multiply contact information to a file, but when i print more then 1 contact, only 1 contact is displayed in the file..
i tried to debug that but i cant find any mistake
i will put the code of my classes here:
This is Demo Class which i run the code from
public class Demo {
public static void main(String[] args) {
System.out.println("Insert number of Contacts:");
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
Contact[] contacts = new Contact[val];
for(int i = 0 ; i < val; i++) {
System.out.println("Contact #"+(i+1));
System.out.print("Owner: \n");
String owner = scanner.next();
System.out.print("Phone number: \n");
String phoneNum = scanner.next();
System.out.print("Please Select Group:\n"
+ "1 For FRIENDS,\n" +
"2 For FAMILY,\n" +
"3 For WORK,\n" +
"4 For OTHERS");
int enumNum = scanner.nextInt();
Group group;
switch(enumNum) {
case 1:
group=Group.FRIENDS;
break;
case 2:
group=Group.FAMILY;
break;
case 3:
group=Group.WORK;
break;
default:
group=Group.OTHERS;
}//switch end
contacts[i] = new Contact(owner,phoneNum,group);
}//loop end
System.out.println("Insert File name");
String fileName = scanner.next();
File f=null;
for(int i = 0 ; i < val; i++) {
if(i==0) {
f = new File(fileName);
contacts[0].Save(fileName);
}
else {
contacts[i].Save(f);
}
}
}
}
This is Contact Class:
enum Group {
FRIENDS,
FAMILY,
WORK,
OTHERS
};
public class Contact {
private String phoneNumber,owner;
private Group group;
PrintWriter pw = null;
public Contact(String owner ,String phoneNumber,Group group) {
setPhoneNumber(phoneNumber);
setOwner(owner);
setGroup(group);
}
public Contact(String fileName) {
File file = new File(fileName+".txt");
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public Contact(File file) {
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
if(f.createNewFile()) {
System.out.println("File created");
pw = new PrintWriter(f); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
}
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
public void Save(File f) {
PrintWriter pw=null;
try {
pw = new PrintWriter(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.println(phoneNumber+"\n"+owner+"\n"+group);
pw.close();
}
public String toString() {
return phoneNumber+"\n"+owner+"\n"+group;
}
}
Every time you create PrintWriter the file is being overwritten. Since you create a new PrintWriter for each contact, the file contains only the last contact information. What you should do is to create PrintWriter only once and use it for all contacts.
Firstly, let's create a new save method with such signature:
public void save(PrintWriter writer)
I have also used the lowercase name of the method due to Java naming convention.
Now the implementation of save method will look like this:
writer.println(phoneNumber);
writer.println(owner);
writer.println(group + "\n\n\n");
Then we should replace the usage of Save method with the new one. Here is your code:
String fileName = scanner.next();
File f = null;
for (int i = 0; i < val; i++) {
if(i == 0) {
f = new File(fileName);
contacts[0].Save(fileName);
} else {
contacts[i].Save(f);
}
}
In order to fix the issue we can change it like this:
String fileName = scanner.next();
File file = new File(fileName);
try (PrintWriter writer = new PrintWriter(file)) {
for (int i = 0; i < val; i++) {
contacts[i].save(writer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I have also used try-with-resources which closes the PrintWriter automatically.
From the Javadoc of the constructor of PrintWriter:
public PrintWriter(File file)
Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
In the Save function you create a PrintWriter everytime. So everytime the file is truncated, and then you lose the contact you saved before.
Since File I/O classes in java use Decorator Design pattern, you can use a FileWriter to take advantage of appending to a file. So you can use this code for Save() method :
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
//System.out.println("File created"); You don't need to create new file.
FileWriter fw=new FileWriter(f,true):// second argument enables append mode
pw = new PrintWriter(fw); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
When making a registration class for registration and login system, it successfully adds the user into the text file. What I am asking is how I can make the program check if user's login ID already exists in text file.
Contents of text file:
User{nickname= Barry, loginID= baz15, password= dan}
When entering the same details for registering, it adds this again. How can I make it not add this again to the file and instead displays a JOptionPane?
I have an array list that references User class to check if the user exists in the text file. This is my code so far:
public class RegistrationJFrame extends javax.swing.JFrame {
ArrayList<User> users = new ArrayList<>();
public RegistrationJFrame() {
initComponents();
lblErrorMessage.setVisible(false);
}
private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {
String nickname = edtNickname.getText();
String loginID = edtLoginID.getText();
String password = String.valueOf(edtPassword.getPassword());
String confirmPassword = String.valueOf(edtReenterPassword.getPassword());
if (!password.equals(confirmPassword)) {
lblErrorMessage.setText("Passwords do not match");
}
if (nickname.equals("") || loginID.equals("") || password.equals("")) {
lblErrorMessage.setText("You must fill in the text fields");
}
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getLoginID().equals(loginID)) {
JOptionPane.showMessageDialog(null, "User exists in file");
} else {
JOptionPane.showMessageDialog(null, "User does not exist");
}
}
try {
User user = new User(nickname, loginID, password);
users.add(user);
File filename = new File("userinfo.txt");
if (!filename.exists()) {
filename.createNewFile();
}
FileWriter fw = new FileWriter(filename, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(user.toString());
bw.newLine();
bw.close();
} catch (Exception e) {
System.out.println("");
}
}
}
A simple fix would be to rewrite your users to the file instead of appending the new user to your file. This means you would just have to loop through the list and rewrite all the users to file each time a new user is created. You could create a saveToFile() method like so and call it
private void saveToFile()
{
try{
File filename = new File("userinfo.txt");
if (!filename.exists()) {
filename.createNewFile();
}
FileWriter fw = new FileWriter(filename, false); //false so you don't append and overwrite
BufferedWriter bw = new BufferedWriter(fw);
//now loop your arraylist of users to resave them to your file
for(User currUser : users)
{
bw.write(currUser.toString());
bw.newLine();
}
bw.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
Next you have to determine when it's ok to add the user and save it. Try using a boolean in your btnRegisterActionPerformed method like this
private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {
String nickname = edtNickname.getText();
String loginID = edtLoginID.getText();
String password = String.valueOf(edtPassword.getPassword());
String confirmPassword = String.valueOf(edtReenterPassword.getPassword());
if (!password.equals(confirmPassword)) {
lblErrorMessage.setText("Passwords do not match");
}
if (nickname.equals("") || loginID.equals("") || password.equals("")) {
lblErrorMessage.setText("You must fill in the text fields");
}
boolean addUser = true;
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getLoginID().equals(loginID)) {
JOptionPane.showMessageDialog(null, "User exists in file");
addUser = false;
break;//no need to keep checking so break out of the for loop
} else {
JOptionPane.showMessageDialog(null, "User does not exist");
}
}
if(addUser)
{
User user = new User(nickname, loginID, password);
users.add(user);
//now save the contents of the list to the file
saveToFile();
}
}
You are currently always adding the user to your file which is incorrect. We use the boolean to determine if the user does not exist, and only when the user cannot be found do we add the user and save to the file.
If I understood you correct I would do it with a separate method:
public class RegistrationJFrame extends javax.swing.JFrame {
ArrayList<User> users = new ArrayList<>();
public RegistrationJFrame() {
initComponents();
lblErrorMessage.setVisible(false);
}
private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {
String nickname = edtNickname.getText();
String loginID = edtLoginID.getText();
String password = String.valueOf(edtPassword.getPassword());
String confirmPassword = String.valueOf(edtReenterPassword.getPassword());
if (!password.equals(confirmPassword)) {
lblErrorMessage.setText("Passwords do not match");
}
if (nickname.equals("") || loginID.equals("") || password.equals("")) {
lblErrorMessage.setText("You must fill in the text fields");
}
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getLoginID().equals(loginID)) {
JOptionPane.showMessageDialog(null, "User exists in file");
} else {
JOptionPane.showMessageDialog(null, "User does not exist");
User user = new User(nickname, loginID, password);
users.add(user);
saveUser(user);
}
}
}
private void saveUser(User user) {
try {
File filename = new File("userinfo.txt");
if (!filename.exists()) {
filename.createNewFile();
}
FileWriter fw = new FileWriter(filename, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(user.toString());
bw.newLine();
bw.close();
} catch (Exception e) {
System.out.println("");
}
}
}
For your file you maybe go better with a json file. Might be easier if you want to add further information to the user.
I'm creating an app in which I need to create account and log into first.
I thought that I can use HashMap for it, where login is my key and password is my value.
Unfortunately, I've got problem with log into account that I've created.
Here is class with methods that take responsible for log. There is problem with checkIfLoginDataIsIncorrect
void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
if (loginDetails.containsKey(login)
&& loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
Main.java:
AccountMaker accountMaker = new AccountMaker();
AccountLogger accountLogger = new AccountLogger();
//I'VE WRITTEN IT JUST FOR CHECK:
HashMap<String, String> loginDetails = accountMaker.getLoginDetails();
loginDetails.put("lala","papa");
[...]
case 2:
while (loopIsTrue) {
accountLogger.inputLoginAndPassword();
if(!accountLogger.checkIfLoginDataIsIncorrect()) {
loopIsTrue = false;
} else {
loopIsTrue = true;
}
}
break;
AccountMaker.java:
public class AccountMaker {
private HashMap<String, String> loginDetails = new HashMap<>();
private String login, password;
private Scanner input = new Scanner(System.in);
[...]
HashMap<String, String> getLoginDetails() {
return loginDetails;
}
}
AccountLogger.java:
public class AccountLogger {
private AccountMaker accountMaker = new AccountMaker();
private Scanner input = new Scanner(System.in);
private HashMap<String, String> loginDetails = accountMaker.getLoginDetails();
private String login, password;
void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
//I'VE WRITTEN IT JUST FOR CHECK
System.out.println(login);
System.out.println(password);
///
if (loginDetails.containsKey(login) && loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
}
For example, if I write loginDetails.put("lala","papa"); and then I want to log into this acc program says Bad login or password.
The issue you're running into is you're polling the wrong HashMap
Create AccountMaker
The AccountMaker makes a new HashMap
Create 'AccountLogger'
The AccountLogger makes a new AccountMaker
The AccountMaker makes a new HashMap
We end up with two different instances of AccountMaker, and their different HashMaps
Try using the same AccountMaker that your AccountLogger uses, or pass it to the constructor
Using constructor:
//Main.java
AccountMaker accountMaker = new AccountMaker();
AccountLogger accountLogger = new AccountLogger(accountMaker);
//AccountLogger.java
class AccountLogger
{
private AccountMaker accountMaker;
public AccountLogger(AccountMaker maker)
{
accountMaker = maker;
}
}
Getting the same AccountMaker:
//Main.java
AccountLogger accountLogger = new AccountLogger();
AccountMaker accountMaker = accountLogger.getAccountMaker();
//AccountLogger.java
public AccountMaker getAccountMaker()
{
return accountMaker;
}
I am trying to understand your problem and have written below sample program to meet your requirement. Compare your code and see if you can fix your issue. If not, can you modify below code and let me know where it is failing.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Testlogin {
static Scanner input = new Scanner(System.in);
static Map<String, String> loginDetails = new HashMap<String, String>();
static String login,password;
static void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
if (loginDetails.containsKey(login)
&& loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
loginDetails.put("lala", "papa");
inputLoginAndPassword();
boolean loopIsTrue =true;
Testlogin testlogin = new Testlogin();
while (loopIsTrue) {
// Testlogin.inputLoginAndPassword();
System.out.println("You have entered login = "+login);
System.out.println("You have entered password = "+password);
if(!testlogin.checkIfLoginDataIsIncorrect()) {
loopIsTrue = false;
} else {
inputLoginAndPassword(); // bad login detected so asking for correct details again.
loopIsTrue = true;
//
}
}
//break;
}
}
I am coding a login program that allows you to set and store a password and username in two separate files (named accordingly). My problem is I can't figure out how to set a username to a password. Ex: Username is Bob, Password is cat, and the user needs to input Bob as the username and cat as the password or else it gives an error(if the user inputs the username as bill and the password as cat, it should detect that the username doesn't go with its respective password). Any help would be nice. *I have not added the username part yet as it is structured the same as the password part, I just need the username to correspond with the password so that the user cannot use a different username with the same password
Here is my code I have so far for a reference:
import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileReader;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class PassCode
{
static String adminPassword = "Change Password";
public static void fileMaker() throws IOException
{
PrintStream standard = System.out;
File f = new File("Password.txt");
FileOutputStream fs= new FileOutputStream(f);
PrintStream ps = new PrintStream(fs);
System.setOut(ps);
String theMessage = "Set New Password";
String userInput = JOptionPane.showInputDialog(theMessage);
System.out.println(userInput);
ps.close();
System.setOut(standard);
}
public static void Checker() throws IOException
{
Scanner inputStream = new Scanner(new FileReader("Password.txt")); //Scans declared file for text on the first line
String fileChecker = inputStream.nextLine(); //Sets scanned line into a string variable
if(fileChecker.isEmpty())
{
fileMaker();
}
else
{
int reply = JOptionPane.showConfirmDialog(null, "Would you like to change the current password", "Warning!", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
String inquire = "Type Administrator Password to Proceed";
boolean flag = true;
while(flag == true)
{
String confirm = JOptionPane.showInputDialog(inquire);
if(confirm.equals(adminPassword))
{
fileMaker();
flag = false;
}
else
{
inquire = "Incorrect!" + "\n" + "Retry";
}
}
}
}
}
public static void main(String[] args) throws IOException
{
Checker();
Scanner inputStreamThree = new Scanner(new FileReader("Password.txt"));
String line = inputStreamThree.nextLine();
String question = "Password Please";
Boolean right = true;
while(right == true)
{
String ask = JOptionPane.showInputDialog(question); //Asks for user to input password
if(ask.equals(adminPassword)) //Checks if user input the admin password
{
fileMaker();
Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
line = adminChecker;
}
else if(line.equals(ask)) //Checks if user password is correct
{
System.out.println("Welcome Fellow Programmer to the Now Functioning Password Checker!" +
"\n" + "Date Today: 10/31/2017" +
"\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
right = false;
}
else if(ask != line) //Checks if user password is incorrect
{
question = "Incorrect Password!";
}
}
}
}
If both username and password are located in the same line number in their respective file, then it should be possible to deduct the right password for a given user.
Example:
Username.txt Password.txt
bob cat
alice rabbit
victor salmon
When searching the username, count the line read until you find the username. Then in the password file, read the number of lines and retrieve the password value. Then compare!
I assume this is academic work because storing password in clear in files is a major security hole and should never be allowed on professional project.
I assume that you use only single login but stored on 2 files Password.txt and Username.txt.
Below is my 10 min codes, so you might need to modified if got typo or error.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class PassCodeA {
public static void main(String[] args)
{
Scanner usernameFile = null;
try {
usernameFile = new Scanner(new FileReader("Username.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Username File Missing", "File Missing", JOptionPane.CLOSED_OPTION);
return;
}
Scanner passwordFile = null;
try {
passwordFile = new Scanner(new FileReader("Password.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Password File Missing", "File Missing", JOptionPane.CLOSED_OPTION);
return;
}
String usernameInput = JOptionPane.showInputDialog(null,"Please Enter Username", "Username", JOptionPane.OK_CANCEL_OPTION);
String passwordInput = JOptionPane.showInputDialog(null,"Please Enter Password", "Username", JOptionPane.OK_CANCEL_OPTION);
System.out.println(usernameInput);
boolean usernameFound = false;
while(usernameFile.hasNextLine()){
final String lineFromFile = usernameFile.nextLine();
if(lineFromFile.equals(usernameInput)){
usernameFound = true;
break;
}
}
if (usernameFound == false) {
JOptionPane.showMessageDialog(null, "Username not found", "Username Not Found", JOptionPane.CLOSED_OPTION);
return;
}
boolean passwordFound = false;
while(passwordFile.hasNextLine()){
final String lineFromFile = passwordFile.nextLine();
if(lineFromFile.equals(passwordInput)){
passwordFound = true;
break;
}
}
if (passwordFound == false) {
JOptionPane.showMessageDialog(null, "Password not found", "Password Not Found", JOptionPane.CLOSED_OPTION);
return;
}
JOptionPane.showMessageDialog(null, "Thank you for login", "Success", JOptionPane.CLOSED_OPTION);
}
}
If you had multiple login credential in that both files. You should use LineNumberReader instead of scanner. So that you can match with line number on both files.
I found a way to implement LineNumberReader(LNR) and have the program check if the line numbers for both the username and password are the same. I used a separate method and called it in the main method. I tested the code and it worked with multiple username info and password info in both files. I know this is messy as well, but I was going for functionality first. Then I will optimize it accordingly. I cannot upload the whole code as it is way to big for space given.
Here is the code I added(just the method with the LNR):
public static void reader() throws IOException
{
JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
"Username:", username,
"Password:", password
};
int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
boolean right = true;
while(right == true)
{
int u = 0;
String userCheck;
FileReader ur = null;
LineNumberReader lnru = null;
try {
ur = new FileReader("username.txt");
lnru = new LineNumberReader(ur);
while ((userCheck = lnru.readLine()) != null)
{
if (userCheck.equals(username.getText()))
{
break;
}
else
{
u = lnru.getLineNumber();
}
}
} catch(Exception e)
{
e.printStackTrace();
} finally {
if(ur!=null)
ur.close();
if(lnru!=null)
lnru.close();
}
int p = 0;
String passCheck;
FileReader pr = null;
LineNumberReader lnrp = null;
try {
pr = new FileReader("Password.txt");
lnrp = new LineNumberReader(pr);
while ((passCheck = lnrp.readLine()) != null)
{
if (passCheck.equals(password.getText()))
{
break;
}
else
{
p = lnrp.getLineNumber();
}
}
} catch(Exception e)
{
e.printStackTrace();
} finally {
if(pr!=null)
pr.close();
if(lnrp!=null)
lnrp.close();
}
if (option == JOptionPane.OK_OPTION)
{
if(password.getText().equals(adminPassword)) //Checks if user input the admin password
{
passMaker();
Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
//lineFromFile = adminChecker;
}
else if(p == u) //Checks if username and password are correct
{
System.out.println("Welcome Fellow Programmer to the Now Functioning login program!" + "\n" + "Date Today: 10/31/2017" + "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
right = false;
}
else //Checks if user password is incorrect
{
option = JOptionPane.showConfirmDialog(null, message, "Login Failed Try Again", JOptionPane.OK_CANCEL_OPTION);
}
}
}
}
I am just trying to output a previously created ArrayList to serialise it for future storage.
but when I attmept to do so I get the runTime error "notSerialisableException: Department.
Is their a speicial way of serializing an arrayList??
Would someone be able to tell me why I may be getting this error.
This is the code:
import java.awt.*;
import java.util.*;
import java.io.*;
import java.io.Serializable;
public class tester1ArrayListObjectSave
{
private ArrayList <Department> allDeps = new ArrayList<Department>();
private int choice = 0;
private String name;
private String loc;
Department theDepartment;
Scanner scan;
public static void main(String[] args)
{
new tester1ArrayListObjectSave();
}
public tester1ArrayListObjectSave()
{
scan = new Scanner(System.in);
options();
}
public void options()
{
System.out.println("wadya wanna do");
System.out.println("1. create a new department");
System.out.println("2. read from text file");
System.out.println("4. save it to system as a serializable file");
System.out.println(". read from text file");
System.out.println("3. to exit");
choice = scan.nextInt();
workOutOptions();
}
public void workOutOptions()
{
if (choice ==1)
{
createNewEmp();
}
else if (choice ==2)
{
try
{
readTextToSystem();
}
catch (IOException exc)
{
System.out.println("uh oh their was an error: "+exc);
}
}
else if (choice == 3)
{
System.exit(0);
}
else if (choice ==4)
{
try
{
createSerialisable();
}
catch (IOException exc)
{
System.out.println("sorry could not serialise data cause of this:"+exc);
}
}
else
{
System.out.println("do nothing");
}
}
public void createNewEmp()
{
System.out.println("What is the name");
name = scan.next();
System.out.println("what is the chaps loc");
loc = scan.next();
try
{
saveToSystem();
}
catch (IOException exc)
{
// do something here to deal with problems
}
theDepartment = new Department(name,loc);
allDeps.add(theDepartment);
options();
}
public void saveToSystem() throws IOException
{
FileOutputStream fos = new FileOutputStream( "backUp.txt", true );
PrintStream outFile = new PrintStream(fos);
System.out.println("added to system succesfully");
outFile.println(name);
outFile.println(loc);
outFile.close();
options();
}
public void readTextToSystem() throws IOException
{
Scanner inFile = new Scanner ( new File ("backUp.txt") );
while (inFile.hasNextLine())
{
name=inFile.nextLine();
System.out.println("this is the name: "+name);
loc = inFile.nextLine();
System.out.println("this is the location: "+loc);
Department dDepartment = new Department(name,loc);
allDeps.add(dDepartment);
options();
}
System.out.println(allDeps);
}
public void createSerialisable() throws IOException
{
FileOutputStream fileOut = new FileOutputStream("theBkup.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allDeps);
options();
}
}
ArrayList isn't the problem; your Department object is.
You need to implement the Serializable interface in that object.