Results 1 to 7 of 7
  1. #1
    Indegon is offline Member
    Join Date
    Nov 2010
    Location
    My own world
    Posts
    15
    Rep Power
    0

    Default File Read Problem

    Ok here's my problem, I am trying to make a login screen for class. The assignment was that the login screen was supposed to be able to read and write information to a series of log files so that upon re-launch the program would have all the prior usernames read in so that you wouldn't have to keep adding the names. In addition there was a user settings file that stored the information for the remember me button so that if you had checked remember me the name would auto populate. I've gotten about 80% done but I hit a major snag. For whatever reason, the file reader isn't working properly. It always completely wipes my file before the read so that all it sees is null. I know it's the reader because I commented the reader out and ran it and it writes the information just fine. It's only when I try to read in the file that the wipe occurs, can someone please take a look at my code and steer me in the right direction? Thank you in advance :)

    Java Code:
    package javaAIO;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    
    public class Login 
    {
    	public static void main(String[] args) throws Exception
    	{
    		class userLog extends JFrame 
    		{
    			private static final long serialVersionUID = 1L;
    			// File writers created here
    			BufferedWriter nameOutput = new BufferedWriter(new FileWriter("NameData.txt"));
    			BufferedWriter passOutput = new BufferedWriter(new FileWriter("PWData.txt"));
    			BufferedWriter userOutput = new BufferedWriter(new FileWriter("UserData.txt"));
    			BufferedReader nameInput = new BufferedReader(new FileReader("NameData.txt"));
    			BufferedReader passInput = new BufferedReader(new FileReader("PassData.txt"));
    			BufferedReader userInput = new BufferedReader(new FileReader("UserData.txt"));
    			// Variables declared here
    			int userNumber = 0;
    			String savedName = "";
    			String savedPass = "";
    			
    			// Arrays to hold username/password database created here
    			String[] uName = new String[255];
    			String[] uPword = new String[255];
    			
    			public userLog() throws Exception
    			{
    				for(int j=0;j<254;j++)
    				if(nameInput.readLine()==null)
    				{
    					uName[j]="abcdefghijklmnopqrstuvwxyz";
    					uPword[j]="abcdefghijklmnopqrstuvwxyz";
    				}
    				else
    				{
    					uName[j]=nameInput.readLine();
    					uPword[j]=nameInput.readLine();
    				}
    				// Set layout to grid layout
    				// Grid layout format(rows,columns,hgap,vgap)
    				setLayout(new BorderLayout(5,10));
    	
    				// New Panel Layout
    				final JPanel mainPanel = new JPanel();
    				final JPanel addPanel = new JPanel();
    				mainPanel.setLayout(new GridLayout(5,4,5,5));
    				addPanel.setLayout(new GridLayout(3,2,5,5));
    				add((mainPanel),BorderLayout.CENTER);
    				add((addPanel),BorderLayout.SOUTH);
    				addPanel.setVisible(false);
    				
    				// Build mainPanel Here
    				JLabel userLabel = new JLabel("Username:");
    				mainPanel.add(userLabel);
    				final JTextField userName = new JTextField(25);
    				mainPanel.add(userName);
    				JLabel pWordLabel = new JLabel("Password:");
    				mainPanel.add(pWordLabel);
    				final JPasswordField passWord = new JPasswordField(25);
    				mainPanel.add(passWord);
    				final JCheckBox remMe = new JCheckBox();
    				mainPanel.add(remMe);
    				mainPanel.add(new JLabel("Remember Me"));
    				JButton logIn = new JButton("Login");
    				mainPanel.add(logIn);
    				JButton cancel = new JButton("Cancel");
    				mainPanel.add(cancel);
    				JButton addUser = new JButton("Add User");
    				mainPanel.add(addUser);
    				userName.setText(savedName);
    				passWord.setText(savedPass);
    				
    				// Build addPanel here
    				addPanel.add(new JLabel("Desired Username:"));
    				final JTextField newUserName = new JTextField(25);
    				addPanel.add(newUserName);
    				addPanel.add(new JLabel("Desired Password:"));
    				final JPasswordField newPassWord = new JPasswordField(25);
    				addPanel.add(newPassWord);
    				JButton confirm = new JButton("Confirm");
    				addPanel.add(confirm);
    				JButton deny = new JButton ("Cancel");
    				addPanel.add(deny);
    				
    				// Add User Button Actions
    				addUser.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                        		addPanel.setVisible(true);
                        		mainPanel.setVisible(false);
                        		
                        }
                    });
    				// OK Button Actions
    				logIn.addActionListener(new ActionListener()
                    {
                        @SuppressWarnings("deprecation")
    					public void actionPerformed(ActionEvent e)
                        {
                        	
                        	for(int i=0;i<255;i++)
                        	{
                            	try
                            	{
                            		if(userName.getText().equals("abcdefghijklmnopqrstuvwxyz")||"abcdefghijklmnopqrstuvwxyz".equals(passWord.getText()))
                                	{
                            			JOptionPane.showMessageDialog(null,"This has been fixed! Problem hacker?");
                            			break;
                                	}
                            		else
                            		{
                            			if((uName[i].equals(userName.getText()))&&(uPword[i].equals(passWord.getText())))
                            			{
                            				JOptionPane.showMessageDialog(null, "Welcome "+uName[i]+", logged in successfully!");
                            				if(remMe.isSelected()==true)
                            				{
                            					savedName=userName.getText();
                            					savedPass=passWord.getText();
                            				}
                            				else
                            				{
                            					savedName="";
                            					savedPass="";
                            				}
                            				break;
                            			}
                            			else if(i>=254)
                            			{
                            				JOptionPane.showMessageDialog(null, "Login information is incorrect, please try again!");
                            			}
                            			
                            		}
                            	}
                            	catch(IllegalArgumentException ex)
                            	{
                            		JOptionPane.showMessageDialog(null, "One or more fields possibly left empty, check information and try again!");
                            		break;
                            	}
                            }
                        }
                    });
    				
    				// Cancel Button Actions (Exits program)
    				cancel.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                        try
                        {
                        	for(int n=0;n<254;n++)
                        	{
                        		nameOutput.write(uName[n]);
                        		nameOutput.newLine();
                        		passOutput.write(uPword[n]);
                        		passOutput.newLine();
                        	}
                        	userOutput.write(savedName);
                    		userOutput.newLine();
                    		userOutput.write(savedPass);
                    		userOutput.newLine();
                        	nameOutput.close();
                    		passOutput.close();
                    		userOutput.close();
                        }
                        catch(IOException ex)
                        {
                        	
                        }
                        	System.exit(0);
                        }
                    });
    				
    				// deny Button Actions (Returns to main panel)
    				deny.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                            mainPanel.setVisible(true);
                            addPanel.setVisible(false);
                        }
                    });
    				
    				// confirm Button Actions (adds a new name to the database)
    				confirm.addActionListener(new ActionListener()
                    {
                        @SuppressWarnings("deprecation")
    					public void actionPerformed(ActionEvent e)
                        {
                           if(newUserName.getText().equals("")||newPassWord.getText().equals(""))
                           {
                        	   JOptionPane.showMessageDialog(null,"Username and/or Password was left blank!");
                           }
                           else if(newUserName.getText().equals("abcdefghijklmnopqrstuvwxyz")||newPassWord.getText().equals("abcdefghijklmnopqrstuvwxyz"))
                           {
                        	   JOptionPane.showMessageDialog(null,"Error! This is a protected string, cannot be used for username and/or password!");
                           }
                           else
                           {
                        	  uName[userNumber]=newUserName.getText();
                        	  uPword[userNumber]=newPassWord.getText();
                        	  userNumber++;
                        	  mainPanel.setVisible(true);
                        	  addPanel.setVisible(false);
                        	  
                           }
                        }
                    });
    				
        					
    			}	
    		}
    			userLog welcome = new userLog();
    			welcome.setTitle("Teragen Media Services");
    			welcome.setSize(300,150);
    			welcome.setResizable(false);
    			welcome.setLocationRelativeTo(null);
    			welcome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			welcome.setVisible(true);
    	}
    }

  2. #2
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    That doesn't even look like it should compile. I don't think you can declare a class within a method... It also looks like your password BufferedWriter is writing to a different file than your reader is reading.

    This also looks weird:
    Java Code:
    for(int j=0;j<254;j++)
    if(nameInput.readLine()==null)
    {
    	uName[j]="abcdefghijklmnopqrstuvwxyz";
    	uPword[j]="abcdefghijklmnopqrstuvwxyz";
    }
    else
    {
    	uName[j]=nameInput.readLine();
    	uPword[j]=nameInput.readLine();
    }
    You're reading two lines if the name isn't null (one for the if statement conditional, and one in the else block). Also, do you really want to read passwords from the name input? For clarity, the for loop should go be for(int j=0; j<uName.length; ++j) and should have curly braces. You're actually not even initializing the full 255 Strings in the arrays with your current loop...

    Finally, are you sure that your reader is wiping the files? Check your files with the reader uncommented and make sure, because I've never seen that happen...
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  3. #3
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    I don't think you can declare a class within a method...

    Actually that's quite permissible. (A local class?). And anonymous inner classes are commonplace of course.


    Java Code:
    public class Foo {
        public static void main(String[] args) {
            new Foo().bar();
    
            class Baz {
                void bar() {
                    System.out.println("...and here");
                }
            }
    
            new Baz().bar();
        }
    
        private void bar() {
            System.out.println("Here...");
        }
    }

    I don't know why "new Baz().bar();" with the local class would be preferred to "new Foo().bar();". Local final variables of the enclosing method are accessible to the inner class which might provide some reason.
    Last edited by pbrockway2; 01-23-2011 at 09:06 PM.

  4. #4
    Indegon is offline Member
    Join Date
    Nov 2010
    Location
    My own world
    Posts
    15
    Rep Power
    0

    Default

    1st problem: both lines were not supposed to be nameInput, one was supposed to be pass input so I corrected that part.

    2nd problem: It doesn't read both lines because I tested the else statement using System.out.print("Test") before posting my code here and the test statement never printed regardless of whether the file was empty or not.

    Question: Should I really use the length of uName to determine that loop even though I'm actually populating 2 different arrays in this instance.

    Problem 3: I did comment out the reader, without the reader in place everything works fine, It's only after the reader is un-commented that I end up getting an empty text file where I should be getting the results of the array.

  5. #5
    Indegon is offline Member
    Join Date
    Nov 2010
    Location
    My own world
    Posts
    15
    Rep Power
    0

    Default

    I wanted to let everyone know I fixed the problem.
    Java Code:
    package javaAIO;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    
    public class Login 
    {
    	public static void main(String[] args) throws Exception
    	{
    		
    		class userLog extends JFrame 
    		{
    			public void writeData() 
    			{
    				try
    				{
    				// File writers created here
    				BufferedWriter nameOutput = new BufferedWriter(new FileWriter("NameData.txt"));
    				BufferedWriter passOutput = new BufferedWriter(new FileWriter("PWData.txt"));
    				BufferedWriter userOutput = new BufferedWriter(new FileWriter("UserData.txt"));
                    	for(int n=0;n<254;n++)
                    	{
                    		nameOutput.write(uName[n]);
                    		nameOutput.newLine();
                    		passOutput.write(uPword[n]);
                    		passOutput.newLine();
                    	}
                    	userOutput.write(savedName);
                		userOutput.newLine();
                		userOutput.write(savedPass);
                		userOutput.newLine();
                    	nameOutput.close();
                		passOutput.close();
                		userOutput.close();
                    }
                    catch(IOException ex)
                    {
                    	
                    }
    			}
    			
    			private static final long serialVersionUID = 1L;
    	        
    			// File read instances created here
    			final java.io.File nameInput = new java.io.File("NameData.txt"); 
    			final java.io.File passInput = new java.io.File("PWData.txt");
    			final java.io.File userInput = new java.io.File("UserData.txt");
    	        
    	        // scanner instances created here
    			final Scanner nScan = new Scanner(nameInput);
    			final Scanner pScan = new Scanner(passInput);
    			final Scanner uScan = new Scanner(userInput);
    			
    			// Variables declared here
    			int userNumber = 0;
    			String savedName = "";
    			String savedPass = "";
    			
    			// Arrays to hold username/password database created here
    			String[] uName = new String[255];
    			String[] uPword = new String[255];
    			
    			public userLog() throws Exception
    			{
    				for(int j=0;j<254;j++)
    				{
    					    /** Keep this commented out after first run! */
    					    //uName[j]="abcdefghijklmnopqrstuvwxyz";
    					    //uPword[j]="abcdefghijklmnopqrstuvwxyz";
    						
    						/** comment these two lines out on first run! **/
    						uName[j]=nScan.nextLine();
    						uPword[j]=pScan.nextLine();
    				}
    						savedName=uScan.nextLine();
    						savedPass=uScan.nextLine();
    				
    				// Set layout to grid layout
    				// Grid layout format(rows,columns,hgap,vgap)
    				setLayout(new BorderLayout(5,10));
    	
    				// New Panel Layout
    				final JPanel mainPanel = new JPanel();
    				final JPanel addPanel = new JPanel();
    				mainPanel.setLayout(new GridLayout(5,4,5,5));
    				addPanel.setLayout(new GridLayout(3,2,5,5));
    				add((mainPanel),BorderLayout.CENTER);
    				add((addPanel),BorderLayout.SOUTH);
    				addPanel.setVisible(false);
    				
    				// Build mainPanel Here
    				JLabel userLabel = new JLabel("Username:");
    				mainPanel.add(userLabel);
    				final JTextField userName = new JTextField(25);
    				mainPanel.add(userName);
    				JLabel pWordLabel = new JLabel("Password:");
    				mainPanel.add(pWordLabel);
    				final JPasswordField passWord = new JPasswordField(25);
    				mainPanel.add(passWord);
    				final JCheckBox remMe = new JCheckBox();
    				mainPanel.add(remMe);
    				mainPanel.add(new JLabel("Remember Me"));
    				JButton logIn = new JButton("Login");
    				mainPanel.add(logIn);
    				JButton cancel = new JButton("Cancel");
    				mainPanel.add(cancel);
    				JButton addUser = new JButton("Add User");
    				mainPanel.add(addUser);
    				userName.setText(savedName);
    				passWord.setText(savedPass);
    				
    				// Build addPanel here
    				addPanel.add(new JLabel("Desired Username:"));
    				final JTextField newUserName = new JTextField(25);
    				addPanel.add(newUserName);
    				addPanel.add(new JLabel("Desired Password:"));
    				final JPasswordField newPassWord = new JPasswordField(25);
    				addPanel.add(newPassWord);
    				JButton confirm = new JButton("Confirm");
    				addPanel.add(confirm);
    				JButton deny = new JButton ("Cancel");
    				addPanel.add(deny);
    				
    				// Add User Button Actions
    				addUser.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                        		addPanel.setVisible(true);
                        		mainPanel.setVisible(false);
                        		
                        }
                    });
    				// OK Button Actions
    				logIn.addActionListener(new ActionListener()
                    {
                        @SuppressWarnings("deprecation")
    					public void actionPerformed(ActionEvent e)
                        {
                        	
                        	for(int i=0;i<255;i++)
                        	{
                            	try
                            	{
                            		if(userName.getText().equals("abcdefghijklmnopqrstuvwxyz")||"abcdefghijklmnopqrstuvwxyz".equals(passWord.getText()))
                                	{
                            			JOptionPane.showMessageDialog(null,"This has been fixed! Problem hacker?");
                            			break;
                                	}
                            		else
                            		{
                            			if((uName[i].equals(userName.getText()))&&(uPword[i].equals(passWord.getText())))
                            			{
                            				JOptionPane.showMessageDialog(null, "Welcome "+uName[i]+", logged in successfully!");
                            				if(remMe.isSelected()==true)
                            				{
                            					savedName=userName.getText();
                            					savedPass=passWord.getText();
                            				}
                            				else
                            				{
                            					savedName="";
                            					savedPass="";
                            				}
                            				break;
                            			}
                            			else if(i>=254)
                            			{
                            				JOptionPane.showMessageDialog(null, "Login information is incorrect, please try again!");
                            			}
                            			
                            		}
                            	}
                            	catch(IllegalArgumentException ex)
                            	{
                            		JOptionPane.showMessageDialog(null, "One or more fields possibly left empty, check information and try again!");
                            		break;
                            	}
                            }
                        }
                    });
    				
    				// Cancel Button Actions (Exits program)
    				cancel.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                        	writeData();
                        	System.exit(0);
                        }
                    });
    				
    				// deny Button Actions (Returns to main panel)
    				deny.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent e)
                        {
                            mainPanel.setVisible(true);
                            addPanel.setVisible(false);
                        }
                    });
    				
    				// confirm Button Actions (adds a new name to the database)
    				confirm.addActionListener(new ActionListener()
                    {
                        @SuppressWarnings("deprecation")
    					public void actionPerformed(ActionEvent e)
                        {
                           if(newUserName.getText().equals("")||newPassWord.getText().equals(""))
                           {
                        	   JOptionPane.showMessageDialog(null,"Username and/or Password was left blank!");
                           }
                           else if(newUserName.getText().equals("abcdefghijklmnopqrstuvwxyz")||newPassWord.getText().equals("abcdefghijklmnopqrstuvwxyz"))
                           {
                        	   JOptionPane.showMessageDialog(null,"Error! This is a protected string, cannot be used for username and/or password!");
                           }
                           else
                           {
                        	  uName[userNumber]=newUserName.getText();
                        	  uPword[userNumber]=newPassWord.getText();
                        	  userNumber++;
                        	  mainPanel.setVisible(true);
                        	  addPanel.setVisible(false);
                        	  
                           }
                        }
                    });
    				
        			{
        				
        			}
    			}	
    		}
    			userLog welcome = new userLog();
    			welcome.setTitle("Teragen Media Services");
    			welcome.setSize(300,150);
    			welcome.setResizable(false);
    			welcome.setLocationRelativeTo(null);
    			welcome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			welcome.setVisible(true);
    	}
    }
    Thank you boyo, It took me awhile to get everything you were talking about but it did help. The problem was the reader and it wasn't. The problem was resulting from trying to access the same file using a stream reader & a stream writer simultaneously. By declaring the writers in a function they weren't initialized until the function was called, this fixed the conflict. I only have one problem, it's still not picking up there's a null value so you have to run the program once by commenting out the two lines that read everything, otherwise it works perfectly though. Thank you for all your help everyone.

  6. #6
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    You should probably initialize the scanners directly from the File instances (Scanner scan = new Scanner(new File("fileToScan"));) Also, to handle the problem with missing/unwritten files, catch the FileNotFoundException that should be thrown if one of the files doesn't exist, and while reading a file, check if there is more data using scan.hasNext();

    Pseudocode:
    Java Code:
    Initialize scan as a Scanner //and any other scanners
    for(int i=0; i<arraySize; ++i){
         if(scan.hasNext()){
              array[i] = scan.nextLine();
         }else{
              initialize array(s) to default value
         }
    }
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  7. #7
    Indegon is offline Member
    Join Date
    Nov 2010
    Location
    My own world
    Posts
    15
    Rep Power
    0

    Default

    That does make sense, quick question though, could I combine an conditional statement using the hasNext function to initialize the text files on startup?

    for instance (pseudocode here)
    Java Code:
    int terminator=0;
    do
    {
    try
    {
        if(nScan.hasNext())
        {
            for(int i=0;i<254;i++)
            {
                 uName[i]=nScan.nextLine();
                 uPass[i]=pScan.nextLine();
             }
         else
         {
            for(int i=0;i<254;i++)
            {
                uName[i]="abcdefghijklmnopqrstuvwxyz"; <default db entry avoid null
                pName[i]="abcdefghijklmnopqrstuvwxyz";
            }
         }
         terminator=1;
    }
    catch(FileNotFoundException ex)
    {
             create("NameData.txt");
             create("PWData.txt");
             create("UserData.txt");
             terminator = 0;
    }
    } while(terminator==0)
    this is just pseudocode but I believe the concept is here, I think this would solve my automation problem wouldn't it?

Similar Threads

  1. problem read pdf file..
    By aly in forum Advanced Java
    Replies: 0
    Last Post: 10-02-2010, 02:06 PM
  2. Problem with JXL: unable to read GSEA xls file
    By angeloulivieri in forum Advanced Java
    Replies: 3
    Last Post: 05-10-2010, 01:53 PM
  3. Replies: 2
    Last Post: 05-11-2009, 11:07 AM
  4. Replies: 0
    Last Post: 02-11-2009, 10:53 AM
  5. How to read a text file from a Java Archive File
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-08-2008, 10:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •