저는 사용자가 자금을 예금하거나 인출 할 때 텍스트 파일의 잔액을 그에 맞게 업데이트해야하는 은행 시스템을 작성하고 있습니다.JAVA에서 텍스트 파일의 행을 어떻게 업데이트합니까?
void saveFiles(int index) throws IOException{
DateFormat dateFormat = new SimpleDateFormat("E MM/dd/yyyy hh:mm:ss a");
Date date = new Date();
BufferedWriter twriter = new BufferedWriter(new FileWriter("Transactions.txt", true));
BufferedWriter fwriter = new BufferedWriter(new FileWriter("Customers.txt", true));
PrintWriter outputFile = new PrintWriter(fwriter);
PrintWriter output = new PrintWriter(twriter);
//update to Customer.txt file
outputFile.println(people[index].getCustID() + "," +people[index].getTitle() + "," +people[index].getfName() + ","+people[index].getlName()+ ","
+people[index].getUsername() + "," +people[index].getPassword() + ","+people[index].getSSN() + ","+people[index].getUniqueID() + ","
+people[index].getSightkey() + ","+ FCA + "," + TSA + "," + people[index].getSoarAcctBal());
//update Transactions.txt file
output.write((dateFormat.format(date) + "," +people[index].getCustID() + "," +numbers[index].getCheckingAcctNum() + "," + transferAmount + "," + "Withdraw" + "," + people[index].getSoarAcctBal()));
outputFile.flush();
outputFile.close();
output.flush();
output.close();
}
고객 파일
//DEFAULT CONSTRUCTOR
public GEBank() {
people = new Customer[4];
}
//LOAD CUSTOMERS FILE
void loadCustomers() throws IOException, FileNotFoundException, ParseException{
BufferedReader inputFile = new BufferedReader(new FileReader("Customers.txt"));
//String that holds current file line.
String custID = "", title = "", fName = "", lName = "", username = "", password = "", SSN = "", uniqueID = "", sightkey = "",
checkingAcctBal = "", savingsAcctBal = "", soarAcctBal = "", line = "";
//Line number of count
int i = 0;
//Read the first customer
line = inputFile.readLine();
//load the array
while (line != null)
{ //Get each item from the line, stopping at the comma separator
StringTokenizer st = new StringTokenizer(line,",");
//Get each token and store it in the array
custID = st.nextToken();
title = st.nextToken();
fName = st.nextToken();
lName = st.nextToken();
username = st.nextToken();
password = st.nextToken();
SSN = st.nextToken();
uniqueID = st.nextToken();
sightkey = st.nextToken();
checkingAcctBal = st.nextToken();
savingsAcctBal = st.nextToken();
soarAcctBal = st.nextToken();
//Instantiate each customer
people[i] = new Customer(Integer.parseInt(custID), title, fName, lName, username, password,
Integer.parseInt(SSN), uniqueID, sightkey, Float.parseFloat(checkingAcctBal), Float.parseFloat(savingsAcctBal), Float.parseFloat(soarAcctBal));
//Get the next customer
i++;
//System.out.println(username);
//Read the next customer
line = inputFile.readLine();
}
inputFile.close();
//System.out.println("The Customer Info file is loaded.");
}
이 내 transferFunds 방법입니다로드. 나는 새로운 균형을 설정하고 파일에 설정된 균형을 쓸 수 있다고 생각했지만, 제대로 작동하지 않아서 잘못했을 수도 있습니다.
//TRANSFER FUNDS METHOD
void transferFunds(int index) throws IOException{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
DateFormat dateFormat = new SimpleDateFormat("E MM/dd/yyyy hh:mm:ss a");
Date date = new Date();
int transferchoice = -1;
do{
System.out.println("\n-- TRANSFER FUNDS MENU --\n");
//transfer from checking to savings
System.out.println("1: Checking Account to Savings Account");
//transfer from savings to checking
System.out.println("2: Savings Account to Checking Account");
System.out.println("\nMake a selection from the above menu options: ");
transferchoice = Integer.parseInt(input.readLine());
//show account numbers of customer
System.out.println("\n-- ACCOUNT NUMBERS --\n");
System.out.println("Checking Account Number: "+numbers[index].getCheckingAcctNum());
System.out.println("Savings Account Number: "+numbers[index].getSavingsAcctNum());
//show account balances of customer
System.out.println("\n-- CURRENT BALANCE --\n");
System.out.println("Checking Account Balance: $"+people[index].getCheckingAcctBal()+".");
System.out.println("Savings Account Balance: $"+people[index].getSavingsAcctBal()+".");
System.out.println("\nHow much would you like to transfer?");
transferAmount = Float.parseFloat(input.readLine());
System.out.println("\nBusiness Date & Time: " + dateFormat.format(date));
//FROM CHECKING TO SAVINGS ACCOUNT
FCA = (people[index].getCheckingAcctBal() - transferAmount);
TSA = (people[index].getSavingsAcctBal() + transferAmount);
//FROM SAVINGS TO CHECKING ACCOUNT
FSA = (people[index].getSavingsAcctBal() - transferAmount);
TCA = (people[index].getCheckingAcctBal() + transferAmount);
saveFiles(index);
if(transferchoice == 1){
System.out.println("\nYou've chosen to transfer $" +transferAmount+ " from your Checking Account to your Savings Account.\n"
+ "\n-- UPDATED BALANCE --\n"
+ "\nChecking Account Balance: $"+FCA+//money[index].setCheckingAcctBal(FCA)
"\nSavings Account Balance: $"+TSA+""
+ "\nFunds successfully transferred"); //confirm the transaction
}else if(transferchoice == 2){
System.out.println("\nYou've chosen to transfer $" +transferAmount+ " from your Savings Account to your Checking Account.\n"
+ "\n-- UPDATED BALANCE --\n"
+ "\nChecking Account Balance: $"+FSA+
"\nSavings Account Balance: $"+TCA+""
+ "\nFunds successfully transferred"); //confirm the transaction
}
if(people[index].getCheckingAcctBal() < transferAmount && people[index].getSavingsAcctBal() < transferAmount){
System.out.println("We're sorry, you do not have sufficient funds to complete this transaction. Transaction Cancelled.\n\n");
return;
}
//Ask customer if they would like to view another balance
System.out.print("\nDo you want to make another transfer? [Enter y/n]: ");
moretransfers = input.readLine().charAt(0);
}while (moretransfers == 'Y' || moretransfers == 'y');
//If moretransfers is no, then show displayLoginMenu method
if (moretransfers == 'N' || moretransfers == 'n')
{ displayLoginMenu(index);}
}
다음은 사용자가 한 계정에서 다른 계정으로 $ 400.00를 이체 한 후 추가 한 텍스트 파일입니다. 그것은 마지막 줄을 만들고 있습니다. 내가하고 싶은 무슨 "사람들 [인덱스]"이 줄을 찾은 다음
100,Ms,Jane,Doe,10ann,guy,1234,brunch,yellow,20000.00,5000.00,2000.00
101,Mr,John,Smith,1mark,girl,2345,lunch,gray,10000.00,3000.00,6000.00
102,Ms,Jenaya,Joseph,2jjPM,jj2,6789,breakfast,green,40000.00,20000.00,80000.00
103,Mr,Edward,Donkor,05001,1005,5432,dinner,blue,25000.00,7100.00,8000.00
101,Mr,John,Smith,1mark,girl,2345,lunch,gray,9600.0,3400.0,6000.0
사람이 도와 드릴 업데이트 된 출력으로 대체하는 것입니다? 나는 연구를 해왔고 임시 파일을 만든 다음 정보를 새 파일로 덮어 쓸 수 있음을 알았습니다. 그러나 나는 이것을 정확하게하는 방법에 관해 아직도 확신이 없다. 저는 아직 Java에 익숙하지 않으므로 도움이 될 것입니다.
파일 인라인을 절대로 변경하지 마십시오!수정 된 내용을 새 파일에 쓴 다음 이전 이름으로 바꿉니다. 또한 은행원 인 경우 고객이 실제로 'float'을 사용하여 감사하지 않을 것입니다 : p – fge
이전 파일의 내용에 신경 쓰지 않는다고 가정하면 고객 배열의 모든 데이터를 수정해야합니다. 업데이트가 필요하다면 배열을 쉼표로 구분 된 텍스트 행으로 변환하는 구문 분석기를 만들어이를 사용하여 이전 파일을 새 데이터로 덮어 씁니다. – Scherling
또한 ArrayList로 사람들 배열을 교환하십시오. 파일에 다른 행을 추가하면 코드가 – Scherling