为何每次运行这个函数后所得到的新文件中,原来的内容每行第一个字符没有读入,例如原文件为:
10000
abc
123
100
5.12
调用该函数并添加新的文本后,此文件就变为:
1000
bc
23
00
.12
......
public void addStock(JMenuBar jmb){
String fileName ="C:\\Stock.doc";
String temp1,temp2,temp3,temp4;
String balance="";
StringBuffer content = new StringBuffer();
float n,f1,f2;
temp1=JOptionPane.showInputDialog("Please input stock name");
temp2=JOptionPane.showInputDialog("Please input stock code");
temp3=JOptionPane.showInputDialog("Please input how many shares you buy");
n=Float.parseFloat(temp3);
temp4=JOptionPane.showInputDialog("Please input share price");
f1=Float.parseFloat(temp4);
try{
BufferedReader in = new BufferedReader(new FileReader(fileName));
balance=in.readLine();
while(in.read()!=-1){
content.append(in.readLine()+'\n');
}
in.close();
}
catch(IOException ioe){
System.out.println("Problem reading "+fileName);
}
f2=Float.parseFloat(balance);
if(f2-f1*n<0){
JOptionPane.showMessageDialog(jmb,"Not enough balance!");
return;
}
try{
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write(new String().valueOf(f2-f1*n));
out.newLine();
out.write(new String(content));
out.newLine();
out.write(temp1);
out.newLine();
out.write(temp2);
out.newLine();
out.write(temp3);
out.newLine();
out.write(temp4);
out.newLine();
out.close();
}
catch(IOException ioe){
System.out.println("Problem writing C:\\Stock.doc");
}
}