ID生成器Java

时间:2015-01-05 07:57:22

标签: java variables

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

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 个答案:

答案 0 :(得分:1)

一种方法是使用数据库序列,或者如果你想在java中这样做,可以使用UUID.randomUUID()