0

谁能给我一个关于在 Java 中保存整数的快速提示。我正在使用计时器制作自定义时钟,并希望在我退出程序时保存时间(或启动自动重启并调用 save 方法)并从停止的地方开始。

我的代码:

MainClass 中的方法:

        t = new Timer();
        tt = new JGameTimer();
        t.scheduleAtFixedRate(tt, 1000, 1000);

Tmer类:

    private static int timeInSeconds = 0, timeInMinutes = 0, timeInHours = 0, timeInDays = 0, timeInYears = 0;
    private int lastTimeInSeconds, lastTimeInMinutes, lastTimeInHours, lastTimeInDays, lastTimeInYears;
    private boolean timeHasBeenSet = false;

    public void run() {
        if (!timeHasBeenSet) {
        timeInSeconds = lastTimeInSeconds;
        timeInMinutes = lastTimeInMinutes;
        timeInHours = lastTimeInHours;
        timeInDays = lastTimeInDays;
        timeInYears = lastTimeInYears;
        timeHasBeenSet = true;
        }else{
        continueTime();
        }
    }

    public void saveTime() {
        lastTimeInSeconds = timeInSeconds;
        lastTimeInMinutes = timeInMinutes;
        lastTimeInHours = timeInHours;
        lastTimeInDays = timeInDays;
        lastTimeInYears = timeInYears;
    }

    public void continueTime() {
        timeInSeconds++;
        if (timeInSeconds == 60) {
            timeInSeconds = 0;
            timeInMinutes++;
        }
        if (timeInSeconds == 10) {
            saveTime();
            System.out.println("Time Saved (Seconds)");
        }
        if (timeInMinutes == 60) {
            timeInMinutes = 0;
            timeInHours++;
        }
        if (timeInMinutes == 2) {
            saveTime();
            System.out.println("Time Saved (Minutes)");
        }
        if (timeInHours == 24) {
            timeInHours = 0;
            timeInDays++;
        }
        if (timeInDays == 2920) {
            timeInDays = 0;
            timeInYears++;
        }
        System.out.println("Time is "+timeInYears+":"+timeInDays+":"+timeInHours+":"+timeInMinutes+":"+timeInSeconds+"");
    }
4

2 回答 2

2

我建议java.io.DataOutputStream与底层一起使用java.io.FileOutputStreamDataOutputStream提供编写原始类型的方法:

DataOutputStream output = new DataOutputStream(
        new FileOutputStream(new File("my-file.dat")));
output.writeInt(someInt);
// ... write more values ...

稍后您可以使用DataInputStream和回读这些内容(以相同的顺序) FileInputStream

或者,您可以编写一个类来保存要保存的数据并使用 Java 的序列化机制来保存/加载它。

于 2013-10-16T03:23:18.837 回答
0

一个快速的提示是将整个时间对象存储到一个文件中。实现接口 Serializable,然后在网上搜索如何使用 ObjectOutputStream 存储/读取可序列化对象。要在关机时添加代码,请查看Running code on program exit in Java

于 2013-10-16T03:22:28.230 回答