将列表保存并加载到文件中

时间:2019-07-11 09:30:34

标签: java eclipse

我目前正在为考试做准备,并且正在从事以下任务:

如何将ArrayList传递给存储列表数据的“保存”方法以及将数据传回的另一个“加载”方法?

class Person {
    private String firstname;
    private String lastname;
    private String sortname;

public Person(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
        updateSortname();

// getter和setter ..

根据任务,我应该使用以下方法:

public static List<Person> load(String filename) throws IOException {
        return ??;
}


public static Person load(DataInputStream in) throws IOException {
        return ??;
}


public static void save(String filename, List<Person> list) throws IOException {
}


public static void save(DataOutputStream out, Person person) throws IOException {
}


public static List<Person> unserialize(String filename) throws IOException, ClassNotFoundException {
        return ??;
}


public static void serialize(String filename, List<Person> persons) throws IOException {
}

这是应产生以下输出的主要方法:

  

[Willy Wonka(WonkaWilly),Charlie Bucket(BucketCharlie),祖父乔   (乔祖父)]

     

[Willy Wonka(WonkaWilly),Charlie Bucket(BucketCharlie),祖父乔   (乔祖父)]

     

[Willy Wonka(WonkaWilly),Charlie Bucket(BucketCharlie),祖父乔   (乔祖父)]

public class PersonTest {

public static void main(String[] args) throws IOException, ClassNotFoundException {
    List<Person> persons = new ArrayList<>();
    persons.add(new Person("Willy", "Wonka"));
    persons.add(new Person("Charlie", "Bucket"));
    persons.add(new Person("Grandpa", "Joe"));
    System.out.println(persons);

    Person.save("persons.sav", persons);
    persons = Person.load("persons.sav");
    System.out.println(persons);
    Person.serialize("persons.ser", persons);
    persons = Person.unserialize("persons.ser");
    System.out.println(persons);
}

}

它应该看起来像这样。但是我不知道如何为ArrayLists做。

public static void save(String filename , Graph graph ) throws IOException{

try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (new FileOutputStream (filename)))) {
out.writeObject (graph);
}
}

public static Graph load (String filename) throws IOException, ClassNotFoundException {

Graph graph = null;
try (ObjectInputStream in = new ObjectInputStream (new BufferedInputStream ( new FileInputStream (filename)))) {
graph = (Graph) in.readObject();
}
return graph;
}

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

public static void save(String filename , ArrayList<Person> persons) throws IOException{

    try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (new FileOutputStream (filename)))) {
        for(int i = 0; i < persons.size; i++){
               out.writeObject(persons.get(i));
        }   
}
}

答案 1 :(得分:1)

由于您需要将Person对象的输出保持原样,因此我们需要覆盖toString()类的Person

  

[Willy Wonka(WonkaWilly),Charlie Bucket(BucketCharlie),Joe爷爷(JoeGrandpa)]

class Person {

//Respective Constructor, Getter & Setter methods


/* Returns the string representation of Person Class. 
 * The format of string is firstName lastName (lastNameFirstName)*/

  @Override
  public String toString() { 
    return String.format(firstName + " " + lastName + "("+ lastName + firstName + ")"); 
  } 
}

有许多方法可以将对象写入文件。这是PrintWriter

将对象保存到文件

public static void save(String filename, List<Person> list) throws IOException {
 PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
 for (Person person : list) {
    pw.println(person.toString());
   }
 pw.close();
}

或使用序列化

//您可以使用序列化机制。 要使用它,您需要执行以下操作:

  1. Person类声明为实现Serializable

    public class Person implements Serializable {
        ...
      @Override
      public String toString() { 
         return String.format(firstName + " " + lastName + "("+ lastName + firstName + ")"); 
      } 
    }
    
  2. 将您的列表写入文件:

    public static void save(String filename, List<Person> list) throws IOException {
     FileOutputStream fos = new FileOutputStream(filename);
     ObjectOutputStream oos = new ObjectOutputStream(fos);
     oos.writeObject(list);
     oos.close();
    }
    
  3. 从文件中读取列表:

    public static List<Person> load(String filename) throws IOException {
     FileInputStream fis = new FileInputStream(filename);
     ObjectInputStream ois = new ObjectInputStream(fis);
     List<Person> list = (List<Person>) ois.readObject();
     ois.close();
     return list;
    }