Results 1 to 7 of 7
Thread: File Read Problem
- 01-23-2011, 06:26 PM #1
Member
- Join Date
- Nov 2010
- Location
- My own world
- Posts
- 15
- Rep Power
- 0
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); } }
- 01-23-2011, 07:07 PM #2
Senior Member
- Join Date
- Mar 2009
- Posts
- 552
- Rep Power
- 5
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:
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...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(); }
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!
- 01-23-2011, 07:58 PM #3
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,561
- Rep Power
- 11
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 08:06 PM.
- 01-24-2011, 12:39 AM #4
Member
- Join Date
- Nov 2010
- Location
- My own world
- Posts
- 15
- Rep Power
- 0
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.
- 01-24-2011, 04:44 PM #5
Member
- Join Date
- Nov 2010
- Location
- My own world
- Posts
- 15
- Rep Power
- 0
I wanted to let everyone know I fixed the problem.
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.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); } }
- 01-25-2011, 05:34 AM #6
Senior Member
- Join Date
- Mar 2009
- Posts
- 552
- Rep Power
- 5
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!
- 01-25-2011, 02:56 PM #7
Member
- Join Date
- Nov 2010
- Location
- My own world
- Posts
- 15
- Rep Power
- 0
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)
this is just pseudocode but I believe the concept is here, I think this would solve my automation problem wouldn't it?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)
Similar Threads
-
problem read pdf file..
By aly in forum Advanced JavaReplies: 0Last Post: 10-02-2010, 01:06 PM -
Problem with JXL: unable to read GSEA xls file
By angeloulivieri in forum Advanced JavaReplies: 3Last Post: 05-10-2010, 12:53 PM -
Read file from directory, update contents of the each file
By svpriyan in forum New To JavaReplies: 2Last Post: 05-11-2009, 10:07 AM -
how to read openproj(Projity) file i.e. ,POD file(Project Management file)
By mahendra.athneria in forum New To JavaReplies: 0Last Post: 02-11-2009, 09:53 AM -
How to read a text file from a Java Archive File
By Java Tip in forum Java TipReplies: 0Last Post: 02-08-2008, 09:13 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks