我需要从文件中显示一个人的更多爱好,但我不知道该怎么做。我需要的是这样的:Stan Ilie : baschet, programare
我的代码在这里:
import java.io.*;
import java.util.*;
public class ListaHobby
{
String line = "";
Hobby h, h1;
Persoana p;
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);
String line1 = "";
String line2 = "";
while ((line1 = br1.readLine()) != null)
{
if (!line1.trim().contains("ID"))
{
String[] attributes = line1.split(";"); // split it at every ";"
p = new Persoana(); // make a new person
p.setId(Integer.parseInt(attributes[0]));
p.setNume(attributes[1]);
p.setPrenume(attributes[2]);
p.setDataNasterii(attributes[3]);
p.setProfesie(attributes[4]);
listOfPersons.add(p);
}
}
while ((line2 = br2.readLine()) != null)
{
if (!line2.trim().contains("ID"))
{
String[] attributes = line2.split(";"); // split it at every ";"
h = new Hobby(); // make a new hobby
h.setId(Integer.parseInt(attributes[0]));
h.setNume(attributes[1]);
h.setDescriere(attributes[2]);
h.setNrPers(Integer.parseInt(attributes[3]));
h.setElemNecesar(attributes[4]);
listOfHobbies.add(h);
}
}
FileWriter fw = new FileWriter("PersHobby.txt");
bw = new BufferedWriter(fw);
for (Persoana p : listOfPersons)
{
for (Hobby h : listOfHobbies)
{
String s = p.getNume() + " " + p.getPrenume() + ": ";
String s1 = h.getNume();
System.out.print(s);
System.out.println(s1);
bw.write(s);
bw.append(s1);
bw.newLine();
}
}
bw.close();
}
catch (IOException ex)
{
System.out.println("Error opening file.");
System.exit(1);
}
}
}
我的输出是这样的:
Stan Ilie: baschet
Stan Ilie: fotbal
Stan Ilie: chitara
Stan Ilie: pianul
Stan Ilie: programarea
Becali GG: baschet
Becali GG: fotbal
Becali GG: chitara
Becali GG: pianul
Becali GG: programarea .....