简体   繁体   中英

Is it possible to create a text file and then on the same run or runtime of the code also read and write in these files? Java

I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.

The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.

Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?

import java.util.Scanner;
import java.io.*;

public class FileManagement {

  static String pathnameFile = "src\\Log";
  static File directory = new File(pathnameFile);
  static String[] allFiles = directory.list();

  public static void createFolder() {
    File logFile = new File(pathnameFile);
    if (!logFile.exists()) {
      logFile.mkdir();
    }
  }
  public static void writeFiles() throws IOException {
    FileWriter writer;
    for (int i = 0; i < allFiles.length; i++) {
      writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
      writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
      writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
      writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
      writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
      writer.close();
    }
  }
//original method
  /*public static void readFiles() {
    Scanner reader;
    for (int i = 0; i < allFiles.length; i++) {
      reader = new Scanner(pathnameFile + allFiles[i]);
    }
  }*/
//My solution
  public static void readFiles() throws IOException{
        if(directory.exists() == false || allFiles == null) {
            return;
        }
        Scanner reader;
        File currentFile;
        String[] data = new String[4];
        for(int i = 0; i < allFiles.length; i++) {
            currentFile = new File(pathnameFile + "\\" +allFiles[i]);
            reader = new Scanner(currentFile);
            int count = 0;
            while(reader.hasNextLine()) {
                if(!reader.hasNext()) {
                    break;
                }
                reader.next();
                data[count] = reader.next();
                count++;
            }
            reader.close();
            String accountName = data[0];
            String PIN = data[1];
            int balance = Integer.parseInt(data[2]);
            eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
        }
    }
}
import java.util.Scanner;
import java.io.*;

public class App {
    public static eBanking currentAccount;
    public static void mainMenu() throws Exception{
        while (true) {
            Scanner input = new Scanner(System.in);
            System.out.println("""
                --------------------------------------------------------
                1. Log in
                2. Register
                0. Exit.
                --------------------------------------------------------
                    """);
            int menuOption = input.nextInt();
            switch (menuOption) {
                case 1 -> {
                    System.out.println("Please enter your account name and PIN below.");
                    System.out.print("Account name: ");
                    String accountName = input.next();
                    System.out.print("PIN: ");
                    String PIN = input.next();
                    System.out.println();

                    for (int i = 0; i < eBanking.accounts.length; i++) {
                        if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
                            eBanking.accounts[i].welcome();
                            currentAccount = eBanking.accounts[i];
                            break;
                        }
                    }
                    menu();
                }
                case 2 -> {
                    System.out.println("Please enter the account name, PIN and inital balance of your new account.");
                    System.out.print("Account name:");
                    String accountNameRegister = input.next();
                    System.out.print("PIN: ");
                    String registerPIN = input.next();
                    System.out.print("Initial balance: ");
                    int initialBalance = input.nextInt();

                    currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
                    menu();
                }
                default -> {
                    FileManagement.writeFiles();
                    System.exit(0);
                }
            }
        }
    }
    public static void menu() {
        Scanner input = new Scanner(System.in); 
        while (true) {
            System.out.println("""
                --------------------------------------------------------
                1. Show your balance.
                2. Withdraw money.
                3. Deposit money.
                4. Change your PIN.
                5. Transfer money to another person.
                0. Back.
                --------------------------------------------------------
                    """);
            int menuOption = input.nextInt();
            switch (menuOption) {
                case 1 -> {
                    currentAccount.showBalance();
                }
                case 2 -> {
                    System.out.println("Please enter the amount you want to withdraw: ");
                    int withdrawAmount = input.nextInt();
                    currentAccount.withdraw(withdrawAmount);
                }
                case 3 -> {
                    System.out.println("Please enter the amount you want to deposit: ");
                    int depositAmount = input.nextInt();
                    currentAccount.deposit(depositAmount);
                }
                case 4 -> {
                    currentAccount.changePIN();
                }
                case 5 -> {
                    System.out.println("Please enter the amount you want to send: ");
                    int amount = input.nextInt();
                    System.out.println("Please enter the account number you want to send the money to: ");
                    String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)  
                    System.out.println("The amount of money is completed");
                    currentAccount.transfer(amount, transferAccount);
                }
                case 0 -> {
                    return;
                }
                default -> {
                    System.out.println("Please enter a number from the menu list!");
                }
            }
        }
    }
    public static void main(String[] args) throws Exception {
        FileManagement.createFolder();
        FileManagement.readFiles();
        mainMenu();
    }
}
import java.util.Scanner;
import java.io.*;

public class eBanking extends BankAccount {
    // Variable declaration
    Scanner input = new Scanner(System.in);
    private String accountName;
    private String accountID;

    public static eBanking[] accounts = new eBanking[100];

    // Methods
    public String getAccountName() {
        return accountName;
    }
    public void welcome() {
        System.out.println("---------------------------------------------------------------------------------------");
        System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
    }
    public void transfer(int x, String str) {
        boolean foundID = false;
        withdraw(x);
        if (initialBalance == 0) {
            System.out.println("Transaction failed!");
        } else if (initialBalance < x) {
            for(int i = 0; i < numberOfAccount; i++) {
                if (str.equals(accounts[i].accountID)) {
                    accounts[i].balance += initialBalance;
                    System.out.println("Transaction completed!");
                    foundID = true;
                } 
            }
            if (foundID = false) {
                System.out.println("Account not found. Transaction failed. Deposit reimbursed");
                this.balance += initialBalance;
                return;
            }
        } else {
            for(int i = 0; i <= numberOfAccount; i++) {
                if (str.equals(accounts[i].accountID)) {
                    accounts[i].balance += x;
                    System.out.println("Transaction completed!");
                    foundID=true;
                    return;
                }
            }
            if (foundID = false) {
                System.out.println("Account not found. Transaction failed. Deposit reimbursed");
                this.balance += x;
                return;
            }
        }
    }
    // Constructors
    public eBanking(String name){
        int firstDigit = (int)(Math.random() * 10);
        int secondDigit = (int)(Math.random() * 10);
        int thirdDigit = (int)(Math.random() * 10);
        int forthDigit = (int)(Math.random() * 10);
        accountID = this.toString();

        PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha 
        balance = 0;                                                                //dhe nuk duhet ta perseris per the gjitha
        accountName = name;
        accounts[numberOfAccount] = this;
        numberOfAccount++;

        System.out.println("---------------------------------------------------------------------------------------");
        System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
    }
    public eBanking(String name, String pin, int x){
        if (checkPIN(pin) == false) {
            System.out.println("Incorrect PIN format!");
            return;
        }
        accountID = this.toString();
        accountName = name;
        balance = x;
        PIN = pin;
        accounts[numberOfAccount] = this;
        numberOfAccount++;

        welcome();
    }
}
import java.util.Scanner;

public abstract class BankAccount {
    // Variable declaration
    protected String PIN;
    protected int balance;

    public static int numberOfAccount = 0;
    protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();

    //Methods
    //Balance
    public int getBalance() {
        return balance;
    }
    public void showBalance() {
        System.out.println("The total balance of the account is " + balance);
    }
    public void withdraw(int x) {
        initialBalance = balance;
        if (balance == 0) {
            System.out.println("The deduction has failed due to lack of balance!");
            return;
        }
        if (balance < x) {
            balance = 0;
            System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
        } else {
            balance -= x;
            System.out.println("The deduction of " + x + " from your balance is completed!");
        }
    }
    public void deposit(int x) {
        balance += x;
        System.out.println("You have made a deposit of  " + x + " and your current balance is " + balance);
    }
    
    //PIN
    public String getPIN() {
        return PIN;
    }
    public void changePIN() {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Please enter your previous PIN: ");
        String tryPIN = input.nextLine();

        if (tryPIN.equals(PIN)) {
            System.out.print("Please enter your new PIN: ");
            String newPIN = input.nextLine();
            if (checkPIN(newPIN) == false) {
                System.out.println("The PIN is not in the correct format!");
            } else {
                System.out.println("The PIN has been changed");
                PIN = newPIN;
            }
        } else {
            System.out.println("The PIN does not match!");
        }
    }
    protected static boolean checkPIN(String str) {
        boolean isValid;

        if(str.length() != 4) {
            isValid = false;
        } else {
            try {
                int x = Integer.parseInt(str);
                isValid = true;
            } catch (NumberFormatException e) {
                isValid = false;
            }
        }
        return isValid;
    }
    //Kjo metode duhet per testim
    public void getDetails() {
        System.out.println(balance + " and PIN " + PIN);
    }
}

I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.

I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.

I have provided all the current code on my program and the fix I implemented on FileManagment class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM