创建同一对象的多个对象

时间:2015-03-23 14:03:27

标签: java object serialization organization

您好我正在编写一个存储用户输入的任务的程序。现在我编写了一个Task Object类。我有用于将对象任务序列化到文件上的代码。我不知道如何自动创建和标记任务(例如:task1,task2,task3)。如果用户输入多个任务,我需要能够执行此操作,以便我可以组织它们。基本上:如何自动创建和标记任务,并序列化存储和组织任务的最佳选项?

import java.io.Serializable;

public class Task extends TaskProcessing implements Serializable
{
    //number of the task
   //int taskNumber;
   //how long the task will take to do
   //double lengthOfTask;
   //mm/dd/yyyy date the task is to be worked on
   //String date;
   //low medium high priority
   //String priority;
   //morning, afternoon, evening, night
   //String timeSlot;
   //hh/mm time the task starts
   String time;
   //work/study/personal categories for the task
   //String catagory;
   //reminders
   //String reminder;

  // There some more variables

   public void setTime(String time)
   {
       this.time = time;
   }

   // There some more variables

   public String getTime()
   {
       return this.time;
   }

   @Override
   public String toString() {
       return new StringBuffer(" Street : ")
       .append(this.time).toString();
   }

}

这是存储对象的代码

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Serializer 
{

public static void serializerTask (String args[]) 
{

   Serializer serializer = new Serializer();
   serializer.serializeTask("1:00");
}

public void serializeTask(String time)
{

   Task task = new Task();
   task.setTime(time);

   try{

    FileOutputStream fout = new FileOutputStream("c:\\task.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fout);   
    oos.writeObject(task);
    oos.close();
    System.out.println("Done");

   }
   catch(Exception ex)
   {
       ex.printStackTrace();
   }
}
}

2 个答案:

答案 0 :(得分:0)

您可以使用某种静态变量,它将作为文件名的前缀或后缀。它应该在使用后改变。如果使用stati字段,给定类的所有对象将使用完全相同的字段(它在所有实例之间共享)

private static Integer suffix=0; // in declaration

FileOutputStream fout = new FileOutputStream("c:\\task"+(suffix++)".ser"); // later in code

这不是线程安全的解决方案,但为了使其线程安全,我们需要使用static AtomicInteger并使用其方法,例如。 getAndIncrement()。这相当于suffix++,但是以线程安全的方式。

答案 1 :(得分:0)

在antoniossss的答案基础上扩展:

为类提供一个idgenerator并为每个实例提供唯一的id。以粗暴的方式,如:

public class Task extends TaskProcessing implements Serializable
{
     private static final AtomicInteger ID_GENERATOR=new AtomicInteger(0);
     private final int id;
     //.....

     public Task()
     {
         id=ID_GENERATOR.getAndIncrement();
         //...
     }
}

然后在文件名中使用该ID作为您编写任务的文件,否则每次保存新任务时都有可能覆盖上次保存的任务。此外,即使您将所有任务追加到同一个文件中,也很难读取(反序列化)一个任务,甚至更难在文件中更新它。

尽管如此,请记住,这种持久存储用户输入数据的方式非常粗糙。您正在有效地实现自己的文件存储。这可能是一个很好的练习,但如果它是更多的东西,你最好通过使用更合适的存储方式,如数据库。

相关问题