2015-01-05 17 views
-1

我试图制作一个程序,您根据自己的身份放入信息,程序会将该信息存储到标题为您自己的ID号的保存文件中,但我不知道如何使程序自动为此生成一个ID。ID生成器Java

import java.io.*; 
import java.util.ArrayList; 

public class SaveObjects{ 

public static void main(String[] arg){ 


    String name="Mike Johnson", ethnicity="White", dob="26101998"; 
    int grade=10; 

    try{ 
     FileOutputStream saveFile=new FileOutputStream("10001.sav"); 
     ObjectOutputStream save = new ObjectOutputStream(saveFile); 

     // Now we do the save. 
     save.writeObject(name); 
     save.writeObject(ethnicity); 
     save.writeObject(dob); 
     save.writeObject(grade); 


     save.close(); 
    } 
    catch(Exception exc){ 
     exc.printStackTrace(); 
    } 

    name="Joe Fok"; ethnicity="Chinese"; dob="02071957"; 
    grade=0; 

    try{ 
     FileOutputStream saveFile=new FileOutputStream("10002.sav"); 


     ObjectOutputStream save = new ObjectOutputStream(saveFile); 


     save.writeObject(name); 
     save.writeObject(ethnicity); 
     save.writeObject(dob); 
     save.writeObject(grade); 


     save.close(); 
    } 
    catch(Exception exc){ 
     exc.printStackTrace(); 
    } 
} 
} 

下面是其他的文件:

import java.io.*; 
import java.util.ArrayList; 

public class RestoreObjects{ 
public static void main(String[] arg){ 
    String name="", ethnicity="", dob=""; 
    int grade=0; 
    try{ 
     FileInputStream saveFile = new FileInputStream("10001.sav"); 
     ObjectInputStream save = new ObjectInputStream(saveFile); 
     name = (String) save.readObject(); 
     ethnicity = (String) save.readObject(); 
     dob = (String) save.readObject(); 
     grade = (Integer) save.readObject(); 
     save.close(); // This also closes saveFile. 
    } 
    catch(Exception exc){ 
     exc.printStackTrace(); // If there was an error, print the info. 
    } 
    System.out.println("\nID: 10001\n"); 
    System.out.println("\tName: "+name); 
    System.out.println("\tEthnicity: " + ethnicity); 
    System.out.println("\tDate of Birth: "+dob); 
    System.out.println("\tGrade: " + grade); 
    System.out.println(); 
    try{ 
     FileInputStream saveFile = new FileInputStream("10002.sav"); 
     ObjectInputStream save = new ObjectInputStream(saveFile); 
     name = (String) save.readObject(); 
     ethnicity = (String) save.readObject(); 
     dob = (String) save.readObject(); 
     grade = (Integer) save.readObject(); 
     save.close(); 
    } 
    catch(Exception exc){ 
     exc.printStackTrace(); 
    } 
    System.out.println("\nID: 10002\n"); 
    System.out.println("\tName: "+name); 
    System.out.println("\tEthnicity: " + ethnicity); 
    System.out.println("\tDate of Birth: "+dob); 
    System.out.println("\tGrade: " + grade); 
    System.out.println(); 
} 
} 

回答

1

的一种方法是使用数据库的序列,或者如果你想要做它用java UUID.randomUUID()