我似乎无法将对象写入文件。它总是以汉字结尾

时间:2019-01-16 10:22:42

标签: java file-handling

我创建了一个注册表单,其中包含一个对象,用于在按下注册按钮时存储用户详细信息。我必须将数据存储在文件(“ ConfidentialAF.txt”)中。数据以中文字符显示在文件上,当我需要检查用户是否存在时,它不会读取文件。

class New_User implements Serializable 
{
String password, username, name;
New_User()
{

}
/*New_User(String pass, String user, String na )
{
    password = pass;
    username = user;
    name = na;


}*/
 }


 public boolean Username_Check(String uname)
{
    int flag = 0;
    try
    {
        FileInputStream fin = new FileInputStream("ConfidentialAF.txt");
        BufferedInputStream bin = new BufferedInputStream(fin);
        ObjectInputStream ois = new ObjectInputStream(bin);
        New_User temp = new New_User();
        while(true)
        {
            if(temp != null)
            {
                temp =(New_User) ois.readObject();
                if(temp.username == uname)
                {
                    flag = 1;
                    break;
                } 
            }    
            else
            {
                break;
            }

        }
        ois.close();
        bin.close();
        fin.close();
    }
    catch (ClassNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    if(flag == 0)           //username does not exists
            return false;
        else                //username exists
            return true;
}



private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    New_User n = new New_User();
    n.name = jTextField2.getText();
    n.username = jTextField5.getText();
    String Password_1 = jPasswordField1.getText();
    String Password_2 = jPasswordField2.getText();
    try
    {

        if(Password_1.equals(Password_2) == true && (Username_Check(n.username) == false))
        {
            FileOutputStream fos = new FileOutputStream("ConfidentialAF.txt");
            BufferedOutputStream bout = new BufferedOutputStream(fos);
            ObjectOutputStream oos = new ObjectOutputStream(bout);
            oos.writeObject(n);
            jLabel5.setText("User Created in Database");
            oos.close();
            bout.close();
            fos.close();
        }
        else if(Password_1.equals(Password_2) == false)
        {
            jLabel5.setText("Error, Password not Matching");
        }
        else if(Username_Check(n.username) == true)
        {
            jLabel5.setText("Username Already exists");
        }
        else
        {
            //Do NOTHING
        }

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

}

0 个答案:

没有答案