0

I recently make a class where it outputs to a .txt file. I want now on a "different class" to read the code (it's a sign up program/sign in) for example, a user registered, and then when he loses his info, he could get them back using a JButton and entering in an scode that he set up once he signed up.. but I know how to make the class read the files but I don't know how will I use them here is the code that outputs:

package malkawi.login;


import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.swing.*;

import malkawi.login.JTextFieldLimit;


/**
 * 
 * @author Defiledx1
 * sign up
 */

public class SignUp extends JFrame implements EventListener {



    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JButton complete = new JButton("Next");
    JLabel fname = new JLabel("Name: ");
    JLabel Mname = new JLabel("Middle Name: ");
    JLabel Lname = new JLabel("Last Name: ");
    JLabel user = new JLabel("Username: ");
    JLabel pass = new JLabel("Password: ");
    JLabel info = new JLabel("Click Next to Continue");
    JLabel email = new JLabel("Email: ");
    JLabel scode = new JLabel("Secret Code: ");
    JTextField fname1 = new JTextField();
    JTextField Mname1 = new JTextField();
    JTextField Lname1 = new JTextField();
    JTextField user1 = new JTextField();
    JPasswordField pass1 = new JPasswordField();
    JTextField email1 = new JTextField();
    JTextField scode1 = new JTextField();
    JRadioButton showPass = new JRadioButton("Show Pass");
    boolean good;


    public SignUp() {
        super("Sign Up - Flare By Malkawi");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(600, 400);
        setResizable(false);
        setVisible(true);
        JTextFieldFilter jtff = new JTextFieldFilter(JTextFieldFilter.NUMERIC);
        jtff.setNegativeAccepted(true);
        setVisible(true);
        setLayout(new GridLayout(0, 2, 10, 10));
        setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        /*
         * Limitations
         */
        fname1.setDocument(new JTextFieldLimit(10));
        Mname1.setDocument(new JTextFieldLimit(1));
        Lname1.setDocument(new JTextFieldLimit(10));
        user1.setDocument(new JTextFieldLimit(15));
        email1.setDocument(new JTextFieldLimit(80));
        //scode1.setDocument(new JTextFieldLimit(5));
        scode1.setDocument(jtff);
        /*
         * End Of Limitations
         */
        /*
         * RadioButton Checked : Unchecked
         */
        showPass.addItemListener(new ItemListener() {
             public void itemStateChanged(ItemEvent e) {          
                 showPassword(e.getStateChange() == 1 ? true : false);

             }           
          });
        /*
         * End of RadioButton Checked : UnChecked
         */
        /*
         * Action of registration
         */
          complete.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e)
                {
                    abilities();
                    if(good == false) {
                        abilities();
                    } else {
                 try {
                    outPutInformation();
                } catch (FileNotFoundException | UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    System.out.println("Flare is unable at the moment!");
                }
                }
                }
            }); 
          /*
           * End of Action of registration
           */
          //  Dimension labelSize = info.getPreferredSize();
          /*
           * Start of placements
           */
            //add(info);
            add(fname);
            add(fname1);
            add(Mname);
            add(Mname1);
            add(Lname);
            add(Lname1);
            add(user);
            add(user1);
            add(pass);
            add(pass1);
            add(email);
            add(email1);
            add(scode);
            add(scode1);
            add(complete);
            add(showPass);
            add(info);
            pack();
    }

    String filename1 = user1.getText();
    String firstname1 = fname1.getText();
     String middlename1 = Mname1.getText();
     String lastname1 = Lname1.getText();
    String username1 = user1.getText();
    @SuppressWarnings("deprecation")
    String password1 = pass1.getText();
    String hotmail1 = email1.getText();
    String secretcode1 = scode1.getText();

    public void abilities() {
        if (firstname1.contains(JTextFieldFilter.ALPHA_NUMERIC)) {//tommorow defiled add more!!
            JFrame abort = new JFrame("Firstname needs to contain numbers and letters");
            JLabel label = new JLabel("Firstname needs to contain numbers and letters");
            abort.setLayout(new BorderLayout());
            abort.setDefaultCloseOperation(EXIT_ON_CLOSE);
            abort.setSize(400, 200);
            abort.setResizable(false);
            abort.add(label, BorderLayout.CENTER);
            abort.pack();
            abort.setVisible(true);
            good = false;
        } else {
            good = true;
        }
    }

    public void showPassword(boolean showP) {
        if (showP == true) {
            pass1.setEchoChar((char)0);
        } else {
            pass1.setEchoChar('*');
        }

    }

    /*
     * File Output Requirements

    String filename = user1.getText();
    String firstname = fname1.getText();
    String middlename = Mname1.getText();
    String lastname = Lname1.getText();
    String username = user1.getText();
    @SuppressWarnings("deprecation")
    String password = pass1.getText();
    String hotmail = email1.getText();
    String secretcode = scode1.getText();

     * File Output done
     */


    public void outPutInformation() throws FileNotFoundException, UnsupportedEncodingException {

        String filename = user1.getText();
        String firstname = fname1.getText();
        String middlename = Mname1.getText();
        String lastname = Lname1.getText();
        String username = user1.getText();
        @SuppressWarnings("deprecation")
        String password = pass1.getText();
        String hotmail = email1.getText();
        String secretcode = scode1.getText();

        PrintWriter writer = new PrintWriter("data/usersaves/"+filename+".txt", "UTF-8");
        writer.println("First Name: "+firstname);
        writer.println("Middle Name: "+middlename);
        writer.println("Last Name: "+lastname);
        writer.println("Username: "+username);
        writer.println("Password: "+password);
        writer.println("Email: "+hotmail);
        writer.println("Secret Code: "+secretcode);
        writer.close();
    }
    }

Thank you!

  • 2
    Can't you reduce this mass of code to the essentials? Is your question "How can I read a text file?" or "How can I use the data I've read from a text file?" In the latter case, I'm afraid that *you* are the one that has to call the shot! – laune Jul 19 '14 at 07:50
  • I'm pretty sure I know what you're saying, but it's unclear how anyone could help you – ChiefTwoPencils Jul 19 '14 at 07:57

4 Answers4

0

Since you want to read the file from a different class and use the data read her, you can try this out.

 Map<String,String> data = new HashMap<>();
FileReader fr = new FileReader(fileToRead);
String str = "";
while((str = fr.readLine()) != null){
   String s = str.split(": ");
   data.add(s[0],s[1]);
 }

 return data;

You can then extract the values from map depending on keys. Now you can call the method of this class which has this code that will return the map of values. Now you can get all that you wrote as

String password = data.get("password");
Niru
  • 732
  • 5
  • 9
0

One side comment, passwords are better kept as char arrays than as strings. You can read further on this post: Why String isn't suitable for parsswoords

Community
  • 1
  • 1
Mateva
  • 786
  • 1
  • 8
  • 27
-1

You can try use a scanner and then iterate over all your lines, a scanner works a little like this:

Scanner fileReader = new Scanner(new File(<File to read>));

while (fileReader.hasNextLine()) {
    String line = fileReader.readLine();
    <Process Line>
}

fileReader.close()

You question it's self is ambiguous as to what you want everything here is from reading to where you have to check your data is included, I can't give you a predefined way for you to work with your own code because it is your code

that is indeed the basics of getting and processing the data, you might want to call a break if the data is found to quickly leave the loop

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Dark Eye
  • 67
  • 2
  • 1
    op says: "I know how to make the class read the files but I don't know how will I use them..." So this is more-or-less useless. – ChiefTwoPencils Jul 19 '14 at 07:56
  • Dark Eye, so after the code you gave(after changing he file to read.), I could just go.. for(line lines : getLines()(is there an already setup getter for get lines?) { and then if(lines.contain("secret code") { actions...? – user3843842 Jul 19 '14 at 08:04
-1

I think what you need is how to store a map to a file, am I right? For this, you have many options. Some of them:

1) use standard object serialization:

Tutorial: http://www.tutorialspoint.com/java/java_serialization.htm

// prepare data
Map<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");

// save to file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("config.ser")));
oos.writeObject(data);
oos.close();

// load from file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("config.ser")));
Object loadedUntyped = ois.readObject();
ois.close();

// you can check type here, etc.
Map<String, String> loadedTyped = (Map<String, String>) loadedUntyped;
System.out.println("loaded: " + loadedTyped);

2) use Properties object:

Tutorial: http://tamanmohamed.blogspot.cz/2012/12/java-storeload-properties-file-in-both.html

// prepare data
Properties data = new Properties();
data.setProperty("key1", "value1");

// save data
data.store(new FileOutputStream(new File("config.properties")), "example");

// load data
Properties loaded = new Properties();
loaded.load(new FileInputStream(new File("config.properties")));
System.out.println("loaded: " + loaded);

3) use your own format: you must first design your own format and implement the right writer/reader (too demanding for this case)

voho
  • 2,805
  • 1
  • 21
  • 26