我有下面的函数,它应该只在对象不在studentlist集中时才写入文件。
我正在使用contains方法。我已经重写了student类中的hashcode和equals方法。集合工作正常,没有打印重复项,但是当我转到文本文件时,同一记录的多个值会出现。
我的主代码:
package fileproject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class FileManipulator {
Set <Student> studentList = new HashSet<Student>();
File file;
public void readData(String f) {
try {
//create a file
file = new File(f);
//instantiate the buffered
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null) {
parseText(line);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseText(String line) {
String [] student = line.split(",");
Student s = new Student(Integer.parseInt(student[0]), student[1], student[2]);
studentList.add(s);
}
public void display() {
studentList.forEach(s -> System.out.println(s));
// studentList.clear();
}
public void appendData(String f, Student s) {
file = new File(f);
if (studentList.contains(s)) return; //I expect this value to be true
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
writer.newLine();
writer.append(s.toString());
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
FileManipulator myFile = new FileManipulator();
myFile.readData("students.txt");
Student st = new Student(4, "Mo Dna", "Genetics");
myFile.appendData("students.txt", st);
myFile.readData("students.txt");
myFile.display();
System.out.println(myFile.studentList.contains(st)); //this should return true but returns false
myFile.studentList.forEach(s -> System.out.println(s));
}
}
我做错什么了?
暂无答案!
目前还没有任何答案,快来回答吧!