我已经完成了文件的读取和写入,但是我遇到了问题。我不知道为什么它只显示文件的最后一行。在从 Person.txt 读取行的部分中,当我退出 while 循环时,我想显示每一行的 p.getName(),它只显示最后一行。我怎样才能解决这个问题?
这是我的代码:
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class ListaHobby {
String line="";
Hobby h = new Hobby();
Persoana p = new Persoana();
BufferedWriter bw = null;
ArrayList<Persoana> listOfPersons;
ArrayList<Hobby> listOfHobbies;
public void writeListaHobbies(){
try{
listOfPersons = new ArrayList<Persoana>();
FileReader file1 =new FileReader("Persoane.txt");
listOfHobbies = new ArrayList<Hobby>();
FileReader file2 = new FileReader("Hobby.txt");
BufferedReader br1 = new BufferedReader(file1);
BufferedReader br2 = new BufferedReader(file2);
while((line1 = br1.readLine()) != null){
if(!line1.trim().contains("ID")){
String[] attributes = line1.split(";");// split it at every ";"
//Person person = new Person(); // make a new person
p.setNume(attributes[1]);
p.setPrenume(attributes[2]);
p.setDataNasterii(attributes[3]);
p.setProfesie(attributes[4]);
listOfPersons.add(p);
}
}
System.out.println(p.getNume());
while((line2 = br2.readLine()) != null){
if(!line2.trim().contains("ID")){
String[] attributes = line2.split(";"); // split it at every ";"
// make a new person
h.setNume(attributes[1]);
h.setDescriere(attributes[2]);
h.setNrPers(attributes[3]);
h.setElemNecesar(attributes[4]);
listOfHobbies.add(h);
}
}
System.out.println(h.getNume());
FileWriter fw = new FileWriter("PersHobby.txt");
bw = new BufferedWriter(fw);
for(int i = 0;i < listOfPersons.size(); i++) {
//for(int j = 0 ; j < listOfHobbies.size();j++) {
if((p.getId())== (h.getId()))
p.addHobby(h);
String s = p.getNume() + " " +p.getPrenume() +
": " + h.getNume() + ", " + h.getNume();
System.out.println(s);
bw.write(s);
bw.newLine();
}
bw.close();
}
catch(IOException ex){
System.out.println("Error opening file.");
System.exit(1);
}
}
}