在Eclipse中写入文件的问题

时间:2015-07-12 03:11:11

标签: java eclipse file-writing

我自己一直在制作一款游戏,而且我在写一个简单的文本文件时遇到了问题,我用它来保存登录面板的数据。我正在使用java.swing创建所有内容。只是想知道是否有人能看到我的问题。

public class Main {

private static String username;
private static String password;

public static void main(String[] args) {

    try { FileWriter fw = new FileWriter("data.txt", true); //creates txt file for data
          PrintWriter pw = new PrintWriter(fw); //creates writer to move data to txt file
        }

    catch (IOException e) { e.printStackTrace(); } //catches error with writing to txt file



    getVariables(); //sets private variables to login info on text file
    login();    //opens login frame
}

public static void login(){

    JFrame frame = new JFrame("");      //creates JFrame for login window

    frame.setResizable(false);                              
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   //FRAME SETTINGS
    frame.setSize(180,140);
    frame.setLocationRelativeTo(null);

    JPanel panel = new JPanel();    //creates panel for login window
    panel.setLayout(null);

    JLabel usernameL = new JLabel("Username:"); //username label for login window
    usernameL.setSize(100,20);
    usernameL.setLocation(5,5);

    JLabel passwordL = new JLabel("Password:"); //password label for login window
    passwordL.setSize(100,20);
    passwordL.setLocation(5,25);


    final JTextField usernameField = new JTextField("",15); //username field for login window
    usernameField.setSize(100,20);
    usernameField.setLocation(70,5);

    final JPasswordField passwordField = new JPasswordField("",15); //password field for login window
    passwordField.setSize(100,20);
    passwordField.setLocation(70,25);

    JButton confirmLogin = new JButton("Log In");       //button to login
    confirmLogin.setSize(80,20);
    confirmLogin.setLocation(45,50);
    confirmLogin.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {        //checks to see if login is correct
            if(usernameField.getText().equals(username) && passwordField.getText().equals(password)){
                gameMenu();         //calls game menu 
            }
            else {
                String message = "Your username or password is wrong!";
                JOptionPane.showMessageDialog                           //displays panel stating login was incorrect
                (new JFrame(), message, "Login Failed",
                JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    JButton createAccount = new JButton("Create Account"); //button to create account
    createAccount.setSize(122,20);
    createAccount.setLocation(25,75);
    createAccount.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {        //calls method to create account
            createAccount();
        }
    });

    panel.add(createAccount);
    panel.add(passwordField);
    panel.add(usernameField);
    panel.add(usernameL);           //add components to window
    panel.add(passwordL);
    panel.add(confirmLogin);

    frame.add(panel);
    frame.setVisible(true);
}

protected static void createAccount() {
    final JFrame frame2 = new JFrame("Account Creation");       //creates window for account creation
    frame2.setSize(290,110);
    frame2.setLocationRelativeTo(null);
    frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);       //window settings
    frame2.setResizable(false);

    JPanel panel2 = new JPanel();
    panel2.setLayout(null);                 //creates panel for account creation window

    JLabel usernameL2 = new JLabel("Username:");
    usernameL2.setSize(100,20);             //creates username label for window
    usernameL2.setLocation(55,5);

    JLabel passwordL2 = new JLabel("Password:");    //creates password label for window
    passwordL2.setSize(100,20);
    passwordL2.setLocation(55,25);

    final JTextField usernameField2 = new JTextField("",15);
    usernameField2.setSize(100,20);             //creates username field for window
    usernameField2.setLocation(120,5);

    final JPasswordField passwordField2 = new JPasswordField("",15);
    passwordField2.setSize(100,20);         //creates password field for window
    passwordField2.setLocation(120,25);

    JButton confirm = new JButton("Confirm Creation");
    confirm.setSize(130,20);            //creates button to confirm account creation
    confirm.setLocation(75,50);
    confirm.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            try { FileWriter fw = new FileWriter("out.txt", false);         //doesnt append (should overwrite data)
              PrintWriter pw = new PrintWriter(fw);                     

              pw.println(usernameField2.getText());         //gets info from textfield and pushes to data txt file
              pw.println(passwordField2.getText());         //gets info from textfield and pushes to data txt file
              pw.close();                               //closes printwriter and saves data file

              String message = "Account created succesfully!";
                JOptionPane.showMessageDialog
                (new JFrame(), message, "",                 //displays panel stating account creation was succesful
                JOptionPane.INFORMATION_MESSAGE);

                frame2.dispose();

        } 
            catch (IOException g) { g.printStackTrace(); }

        }});

    panel2.add(confirm);
    panel2.add(usernameL2);
    panel2.add(passwordL2);         //add components to account creation window
    panel2.add(usernameField2);
    panel2.add(passwordField2);
    frame2.add(panel2);
    frame2.setVisible(true);

}

public static void gameMenu(){

    System.out.println("IT WORKS!");            //testing to make sure filewriting works
}

public static void getVariables(){

    try {
        FileReader fr = new FileReader("data.txt");         //gets ready to read from data file
        BufferedReader br = new BufferedReader(fr);

        String str;
        for(int i = 0; i < 2; i++){
            if((str = br.readLine()) != null && i == 0) {           //reads first line and saves it
                username = str;
            }
            if((str = br.readLine()) != null && i == 1) {           //reads second line and saves it
                password = str;
            }
        }

        br.close();                     //closes reader

    } catch(IOException e) {
        System.out.println("File not found.");
    }

}
}

1 个答案:

答案 0 :(得分:0)

尝试使用:

    for(int i = 0; i < 2; i++){
        if(i == 0 && (str = br.readLine()) != null) {
            username = str;
        }
        if(i == 1 && (str = br.readLine()) != null) {
            password = str;
        }
    }

您正在使用的代码无效,因为即使i不是0,第一个if语句也会使用第二行。

更简单的阅读方式是:

for(int i = 0; (str = br.readLine())!=null && i < 2;i++){
     if(i == 0){
        username = str;
     }else{
        password = str;
     }
}

同样在getVariables()方法中,您应该阅读out.txt文件而不是data.txt。根据您发布的代码,似乎没有数据写入data.txt文件。