0
public class AddMoney {
RegisterAndLogin rl = new RegisterAndLogin();
private String UserName;
File file;
int balance;
String sourceamt;
Scanner scanner = new Scanner(System.in);
String path = "D:\\PesonalAccoutant\\account\\";
String readData;
FileWriter fw;
BufferedWriter bw;
StringBuilder sb;
BufferedReader br;
public AddMoney(String UserName) {
this.UserName = UserName;
}
public void acceptmoneyvalus() throws IOException {
System.out.println("<1> add money to account");
System.out.println("<2> remove money from account");
addmoneytoaccount();
}
public void addmoneytoaccount() throws IOException {
try {
file = new File(path + UserName + ".txt");
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
file.createNewFile();
System.out.println("file create");
if (file.exists()) {
br = new BufferedReader(new FileReader(file));
if (file.length() == 0) {
System.out.println("reading null data");
bw.write("Balance=" + 0);
bw.newLine();
System.out.println("Please enter the amount.");
balance = scanner.nextInt();
System.out.println("Please enter source of the ammount");
sourceamt = scanner.next();
addBalance(balance);
bw.append("Amount=");
bw.append("" + balance);
bw.newLine();
bw.append("Source of the amount=" + sourceamt);
bw.newLine();
bw.newLine();
} else {
System.out.println("else blco");
System.out.println("Please enter the amount.");
balance = scanner.nextInt();
System.out.println("Please enter source of the ammount");
sourceamt = scanner.next();
addBalance(balance);
bw.append("Amount=");
bw.append("" + balance);
bw.newLine();
bw.append("Source of the amount=" + sourceamt);
bw.newLine();
bw.newLine();
}
} else {
System.out.println("try to register again...");
}
} catch (Exception e) {
System.out.println("Error" + e);
} finally {
bw.close();
}
}
private void addBalance(int balance) throws IOException {
try {
int count = 0;
br = new BufferedReader(new FileReader(file));
while ((readData = br.readLine()) != null) {
count++;
sb = new StringBuilder();
if (count == 1) {
sb.append(readData);
sb.delete(0, 8);
System.out.println("full datd is"+readData);
// int i=(Integer)sb;
int i = Integer.valueOf(sb.toString());
int totalbalance = balance + i;
System.out.println("balance is " + sb.toString());
System.out.println("total balnce" + totalbalance);
bw.append("Balance=" + totalbalance);
bw.newLine();
}
}
} catch (Exception e) {
System.out.println("Error " + e);
} finally {
br.close();
}
}
}
我想在第一行添加餘額,但是當我添加更多數據時,它會追加最後兩行而不是文件的開頭。 我希望每一個我加錢時,必須反映在加入量進入我想追加第一行,但它追加多個數據的最後一行
如說但AINT working.still在最後一個記錄追加我所做的更改。 –
餘額= 0 金額= 100 源量=爸 餘額= 100 金額= 100 源量=爸 文本文件的數據。 餘額= 100 金額= 100 金額來源=父親 –