我很困惑如何保存我的数据,例如我hava(学生ID,姓名,姓氏)唯一的学生ID是整数,我想将这些数据保存到文本文件时我按(AddButtton)然后我想要当我按(UpdateButton)时更新这些数据,数据被保存但我每次使用Vector Array时保存括号的数据都会出现在文件中,当按下(UpdateButton)时数据不会返回到我的要更新的TextField。
class BtnListenerAdd implements ActionListener{
public void actionPerformed(ActionEvent a) {
if (a.getSource()==btnAdd){
Student s=new Student(tfname.getText(),tfsurname.getText());
s.number=Integer.parseInt(tfno.getText());
myVector.add(s);
//System.out.println(s);
try{
java.io.RandomAccessFile raf =
new java.io.RandomAccessFile("e:\\random.txt", "rw");
for (int i = 0; i < myVector.size(); i++) {
raf.writeChars(myVector.toString());
}
raf.seek(0);
while (raf.getFilePointer() < raf.length()) {
System.out.println(raf.readChar());
}
raf.close();
}catch(Exception e){
System.out.println( e.toString() );
}
}
if (a.getSource()==btnList){
ta1.setText("");
for (Student s : myVector) {
ta1.append(s.toString()+ "\n");
}
}
}
}
class BtnListenerUpdate implements ActionListener{
public void actionPerformed(ActionEvent s) {
if (s.getSource()==btnUpdate){
Student l=new Student(tfname.getText(),tfsurname.getText());
l.number=Integer.parseInt(tfno.getText());
myVector.add(l);
try{
java.io.RandomAccessFile raf =
new java.io.RandomAccessFile("e:\\random.txt", "rw");
for(int i=0; i <myVector.size(); i++) {
raf.writeChar(myVector.size());
}
raf.seek(0);
int no= raf.readInt();
tfno.setText(no + "");
System.out.println(no);
String nam = "";
for(int x=0; x<50; x++){
nam += raf.readChar();
}
nam = "";
for(int x=0; x<50; x++){
nam += raf.readChar();
}
}catch(Exception e){
System.out.println( e.toString() );
}
}
}
}
答案 0 :(得分:2)
如果您没有创建或更新那么多记录,我建议您使用BufferedWriter。如果您是,我建议您使用Mongo或MySQL
等数据库而且,您可能还想开始使用UTF-8数据测试代码。变形金刚等。 :)
答案 1 :(得分:0)
我建议您在编写之前先编写一些您理解的代码。你写的代码越多,你就越难以解决它。
我会再次开始编写另一个类,您可以使用您可以编写的最简单的代码开始单元测试,并且当它工作时再添加一些并测试它。
不幸的是,你写的一些代码只是废话,这就是为什么我不会重复使用它。