dyonas
dyonas

Reputation: 1

Saved in ArrayLists but wrong output write in a file

Could you please advise what is missing for my code below? My code is running but it didn't write in a file. Inputs where via textfields. Below is what i have.

public class JFrameNewAccount extends javax.swing.JFrame {

 ArrayList<BankAccount> list = new ArrayList<BankAccount>();
 BankAccount account = new BankAccount();


public JFrameNewAccount() {
    initComponents();



 }
private void btnSaveAActionPerformed(java.awt.event.ActionEvent evt) {
account.setAccountName(txt_accountname.getText());
account.setAccountNo(txt_accountnumber.getText()); 

String fileName = "bank.txt";
    FileWriter file = null;

    try {
        file = new FileWriter(fileName,true);
        PrintWriter pw = new PrintWriter(file);
        for(BankAccount str: list) {
            pw.println(str);
        }

       pw.flush();
       pw.println("\n");


    } catch(FileNotFoundException ex) {
       JOptionPane.showMessageDialog(this, "Can't create your account!");

    } catch (IOException ex) {
        Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
       try {
           file.close();
       } catch (IOException ex) {
           Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
       }
    }

Please advise.

Upvotes: 0

Views: 281

Answers (1)

javatarz
javatarz

Reputation: 1202

You should try posting a SSCCE next time.

Your problem is that you've created an ArrayList (viz. "list"), created an object for the ArrayList (viz. "account"), added data to the object (by calling setAccountName and setAccountNo) and tried to write everything in the ArrayList into the file.

At no point, did you set the object into the ArrayList.

I'm assuming you're trying to create a frame that sets data from the screen into the file. If so, this is what I'd do. (changes are in lines 1 and 4 of your ActionPerformed)

Note: I'm not cleaning up your code (if I could nit pick, I'd write it a bit differently). The point of the response is to show you why your code doesn't work, which is what the question is.

public class JFrameNewAccount extends javax.swing.JFrame {

    private List<BankAccount> list = new ArrayList<>();

    public JFrameNewAccount() {
        initComponents();
    }

    private void btnSaveAActionPerformed(java.awt.event.ActionEvent evt) {
        BankAccount account = new BankAccount();
        account.setAccountName(txt_accountname.getText());
        account.setAccountNo(txt_accountnumber.getText()); 
        list.add(account);

        String fileName = "bank.txt";
        FileWriter file = null;

        try {
            file = new FileWriter(fileName,true);
            PrintWriter pw = new PrintWriter(file);
            for(BankAccount str: list) {
                pw.println(str);
            }

           pw.flush();
           pw.println("\n");
        } catch(FileNotFoundException ex) {
           JOptionPane.showMessageDialog(this, "Can't create your account!");
        } catch (IOException ex) {
            Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
           try {
               file.close();
           } catch (IOException ex) {
               Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Update: Just saw your comment. Your solution will not give you the output you need because you're attempting to write an object. You need to override it's toString. Sample below

public class BankAccount {
    private String accountName;
    private String accountNumber;

    @Override
    public String toString() {
        return "Account Name: \"" + accountName + "\"" + System.getProperty("line.separator") + "Account Number: \"" + accountNumber + "\"";
    }

    // Setters and getters here
    public String getAccountName() {
        return accountName;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }
}

Explanation: Streams only write Strings to them. If you try to put an object into System.out.println() you'll get a similarly weird output. The output you see is the default toString() implemented in the Object class in java which shows you the class name and the object's hash code. You can either customise your toString or change the way your write the object to file (by calling getters internally) or the output stream (i.e. System.out.println())

Update 2: If you want to format it with new lines between each field, you can use a "\n" or "\r\n" based on the operating system. It's best to let Java decide which one will work. One of the ways to do that is to use System.getProperty("line.separator") but there are other ways as listed in this wonderful Stack Overflow post asking about platform independent new line characters.

Upvotes: 1

Related Questions