读取和写入.List文件的ArrayList

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读取和写入.List文件的ArrayList相关的知识,希望对你有一定的参考价值。

我不能让我的项目的这部分工作。 (fileOut()和fileIn()方法)。我将不胜感激任何帮助!

我正在尝试构建一个方法来打开一个文本文件,并将类型的ArrayList的详细信息写入其中。

我还尝试构建第二种方法来打开包含所有银行帐户详细信息的文本文件,并使用传入数据使用BankAccount构造函数创建BankAccount对象,并将每个帐户存储在ArrayList中。

请注意,该类中的其他方法需要使用存储在arraylist中的信息。以下是关注(读写)的主要代码:

public void fileOut()
{
    File fileName = new File("BankAccountFiles.txt");
    try{
        FileWriter fw = new FileWriter(fileName);
        Writer output = new BufferedWriter(fw);
        int numEntries = bankAccArrayList.size();
        for (int i = 0; i < numEntries; i++) {
            output.write(bankAccArrayList.get(i).toString() + "
"); 
        }
        output.close();
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(null,"File cannot be created");
    }
}


public void fileIn()
{
    ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
    String line;
    try {
        BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
        if(!input.ready()) {
            throw new IOException();
        }
        while ((line = input.readLine()) != null) {
            aList.add(line);
        }
        input.close();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null,e);
    }
}

这是全班的代码:

import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.swing.*;

public class MyBankController
{

    private ArrayList<BankAccount> bankAccArrayList;


    public MyBankController() 
    {   
        bankAccArrayList = new ArrayList<BankAccount>();
    }

    public void createAccount (String accNum, String custName)
    {   
        bankAccArrayList.add(new BankAccount( accNum,custName));
        printAccountDetails(bankAccArrayList.get(bankAccArrayList.size()-1));
    }

    private void printAccountDetails(BankAccount incomingAcc)
    {   
        JOptionPane.showMessageDialog(null,incomingAcc.toString(),"Account Details",JOptionPane.PLAIN_MESSAGE);
    }

    public void listAllAccounts()
    {  
        String outputStr = "List of all accounts :

";

        for(BankAccount account :  bankAccArrayList){

            outputStr += account + "

";
        }

        JOptionPane.showMessageDialog(null,outputStr,"List of all Accounts",JOptionPane.PLAIN_MESSAGE);
    }

    public void listAllActiveAccounts()
    {  
        String outputStr = "List of all active accounts :

";
        for(BankAccount account :  bankAccArrayList){

            if(account.getActive()) {

                outputStr += account + "

";
            }
        }
        JOptionPane.showMessageDialog(null,outputStr,"List of all Active Accounts",JOptionPane.PLAIN_MESSAGE);
    }

    private int getIndex(String bankAccNum)

    {   
        for (int i = 0; i < bankAccArrayList.size(); i++) {

            if (bankAccNum.equals(bankAccArrayList.get(i).getAccNumber()))
            {
                return i;
            }
        }

        JOptionPane.showMessageDialog(null,"Bank Account Number: " + bankAccNum + " is invalid","Error wrong account number",JOptionPane.ERROR_MESSAGE);
        return -1;
    }

    public void makeWithdrawal(String accNumber, double amount)
    {   
        if(getIndex(accNumber) != -1){ 

            bankAccArrayList.get(getIndex(accNumber)).makeWithdraw(amount);
        }
    }

    public void makeLodgement(String accNumber, double amount)
    {   
        if(getIndex(accNumber) != -1){ 

            bankAccArrayList.get(getIndex(accNumber)).makeLodgement(amount);
        }
    }

    public  void displayAccount(String accNumber)
    {   
        if(getIndex(accNumber) != -1){ 

            JOptionPane.showMessageDialog(null,(bankAccArrayList.get(getIndex(accNumber)).toString()),"Accounts Details",JOptionPane.PLAIN_MESSAGE);
        }
    }

    public  void closeAccount(String accNumber)
    {   
        if(getIndex(accNumber) != -1){ 

            bankAccArrayList.get(getIndex(accNumber)).closeAccount();
        }
    }

     public  void removeAccount(String accNumber)
    {   

        int index = getIndex(accNumber);

        if(index != -1){ 

            BankAccount myAcc = bankAccArrayList.get(index);

            if ((myAcc.getActive() == false) && (myAcc.getAccBalance() == 0)){

                bankAccArrayList.remove(index);

            }else if((myAcc.getActive() == false) && (myAcc.getAccBalance() > 0)){

                int dialogResult = JOptionPane.showConfirmDialog(null," This account has a balance,do you wish to withdraw this balance " + 
                        "so as to remove the account ?"," Balance in inactive account",JOptionPane.PLAIN_MESSAGE);

                if(dialogResult == JOptionPane.YES_OPTION){

                    myAcc.setActive();
                    myAcc.makeWithdraw(myAcc.getAccBalance());
                    myAcc.setActive();
                    bankAccArrayList.remove(index);
                    JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
                }

            } else if((myAcc.getActive() == true) && (myAcc.getAccBalance() == 0)){

                int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status, do you wish to change its status so as to remove account ?"  
                    ,"Account Active",JOptionPane.PLAIN_MESSAGE); 

                if(dialogResult == JOptionPane.YES_OPTION){

                    myAcc.setActive();
                    bankAccArrayList.remove(index);                              
                    JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);

                }

            } else{

                int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status and a balance, do you wish to close the account so as remove it" 
                    ,"Account Active with Balance",JOptionPane.PLAIN_MESSAGE);

                if(dialogResult == JOptionPane.YES_OPTION){

                    myAcc.closeAccount();
                    bankAccArrayList.remove(index);                                
                    JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
                }                
            }
        }
    }


        public void customerInterface() 
    {
        String accNumber = JOptionPane.showInputDialog(null,"Please enter your account number","Account Login",JOptionPane.PLAIN_MESSAGE);
        if(getIndex(accNumber) != -1)
        {
             String numOption = JOptionPane.showInputDialog(null,"Please select an option below:

" + 
            " [1] Make a lodgment:

 [2] Make a withdrawal:

 [3] Display account details:

" +
            " [4] Close account:

 [5] Exit","MyBank ATM",JOptionPane.PLAIN_MESSAGE);
            if (numOption == null) //User presses cancel or 'x'.
            {
                JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE);
            }
            else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
            {
                //Brings up lodgement interface
                String amount = JOptionPane.showInputDialog("Please enter the amount you would like to lodge.");
                makeLodgement(accNumber, Double.parseDouble(amount)); // Lodges amount into account.
                customerInterface(); 
            }
            else if(Integer.parseInt(numOption) == 2)
            {
             String amount = JOptionPane.showInputDialog("Please enter the amount you wish to withdraw.");
             makeWithdrawal(accNumber, Double.parseDouble(amount)); //Call on makeWithdrawl method.
             customerInterface();
            }
            else if(Integer.parseInt(numOption) == 3)
            {
                displayAccount(accNumber); //Calls on displayAccount method.
                customerInterface();
            }
            else if(Integer.parseInt(numOption) == 4)
            {
                closeAccount(accNumber); //Call on close account method.
                customerInterface();
            }
            else if(Integer.parseInt(numOption) == 5)
            {
                return; //Exits system.
            }
            else if(Integer.parseInt(numOption) > 5 || Integer.parseInt(numOption) < 1) //If number enter is outside of 1-5.
            {
              JOptionPane.showMessageDialog(null,"Please enter a number between 1-5 and try again.","Error",JOptionPane.ERROR_MESSAGE);
              customerInterface();
            }   
        }
    }


    public void bankInterface()
    {
            String numOption = JOptionPane.showInputDialog(null,"Please select an option below:

" + 
            " [1] Display All Accounts:

 [2] Display All Active Accounts:

 [3] Open a New Account:

" +
            " [4] Close an Existing Account:

 [5] Run Start of Day:

 [6] Run End of Day:

 [7] Exit:","MyBank System",JOptionPane.PLAIN_MESSAGE);
            if (numOption == null)
            {
                JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE); //User presses cancel or 'x'.
            }
            else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
            {
                //Displays all accounts.
                listAllAccounts();
                bankInterface();
            }
            else if(Integer.parseInt(numOption) == 2)
            {
                //Display all active accounts.
                listAllActiveAccounts();
                bankInterface();
            }
            else if(Integer.parseInt(numOption) == 3)
            {
                //Open a new account
                String accNum = JOptionPane.showInputDialog("Please allocate an account number:");
                String custName = JOptionPane.showInputDialog("Please enter the customers name:");
                createAccount (accNum, custName);
                bankInterface();
            }
            else if(Integer.parseInt(numOption) == 4)
            {
                //Close an existing account.
                String accNumber = JOptionPane.showInputDialog("Please enter the account number you would like to close:");
                closeAccount(accNumber);
                bankInterface();
            }
            else if(Integer.parseInt(numOption) == 5)
            {
                //Run start of day file.
                fileIn();
                bankInterface();
            }
            else if(Integer.parseInt(numOption) == 6)
            {
                //Run end of day file.
                fileOut();
                bankInterface();
            }
            else if(Integer.parseInt(numOption) == 7)
            {
                //Exits system.
                return;
            }
            else if(Integer.parseInt(numOption) > 7 ||Integer.parseInt(numOption) < 1) //If user enters number outside of 1-7.
            {
                JOptionPane.showMessageDialog(null,"Please enter a number between 1-7 and try again.","Error",JOptionPane.ERROR_MESSAGE);
                bankInterface();
            }
    }


    public void fileOut()
    {
        File fileName = new File("BankAccountFiles.txt");
        try{
            FileWriter fw = new FileWriter(fileName);
            Writer output = new BufferedWriter(fw);
            int numEntries = bankAccArrayList.size();
            for (int i = 0; i < numEntries; i++) {
                output.write(bankAccArrayList.get(i).toString() + "
"); 
            }
            output.close();
        }
        catch(Exception e) {
            JOptionPane.showMessageDialog(null,"File cannot be created");
        }
    }


    public void fileIn()
    {
        ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
        String line;
        try {
            BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
            if(!input.ready()) {
                throw new IOException();
            }
            while ((line = input.readLine()) != null) {
                aList.add(line);
            }
            input.close();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null,e);
        }
    }
}
答案

在你的fileIn方法中,你试图将一个字符串添加到ArrayList类型的BankAccount中。 而不是aList.add(line),你应该使用aList.add(new BankAccount(line))。 假设你的BankAccount构造函数只接受一个String参数,这应该可行。 完整方法:

  public void fileIn()
    {
        List<BankAccount> aList = new ArrayList<BankAccount>();
        String line;
        try {
            BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
            if(!input.ready()) {
                throw new IOException();
            }
            while ((line = input.readLine()) != null) {
                aList.add(new BankAccount(line));
            }
            input.close();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null,e);
        }
    aList.forEach(System.out::println); // Java8
    }

我也改变了你的aList使用List界面,并添加了一个lambda来打印最后aList中的每个值。

以上是关于读取和写入.List文件的ArrayList的主要内容,如果未能解决你的问题,请参考以下文章

在 Android 上跨会话从文件中写入然后读取 ArrayList<Object>?

Java - 如何将我的 ArrayList 写入文件,并将该文件读取(加载)到原始 ArrayList?

java 如何用io流 读取list集合里我需要的内容,然后写入到.txt文件里?各位大侠请赐教

java从list中取数,取前三行

delphi stringgrid里的数据到本地txt文件的读取和写入的代码

java ArrayList 如何读取文件中的数据,并且搜索