如何存储要在另一个会话中使用的方法的信息?

时间:2014-11-01 20:30:21

标签: java

所以我正在制作一个程序,用于存储我与一些孩子的会议,我正在辅导。它会密切关注会议时间,讨论以及我完成了多少小时。我知道如何编写所有方法来做到这一点,但我的问题是程序只会保存程序打开的会话信息...如何在程序运行后存储此信息并访问它关闭并再次打开?

这是我在java类中做过的测试得分管理器程序的一些摘录,它有同样的问题......

    public class Student {
    private String name;
    private int test1;
    private int test2;
    private int test3;

    public Student() {
        name = "";
        test1 = 0;
        test2 = 0;
        test3 = 0;
    }
    public Student(String nm, int t1, int t2, int t3){
        name = nm;
        test1 = t1;
        test2 = t2;
        test3 = t3;
    }
    public Student(Student s){
        name = s.name;
        test1 = s.test1;
        test2 = s.test2;
        test3 = s.test3;
    }
public void setName(String nm){
    name = nm;
}
public String getName (){
    return name;
}
public void setScore (int i, int score){
    if (i == 1) test1 = score;
    else if (i == 2) test2 = score;
    else test3 = score;
}
public int getScore (int i){
    if (i == 1)         return test1;
    else if (i == 2)    return test2;
    else                return test3;
}
public int getAverage(){
    int average;
    average = (int) Math.round((test1 + test2 + test3) / 3.0);
    return average;
}
public int getHighScore(){
    int highScore;
    highScore = test1;
    if (test2 > highScore) highScore = test2;
    if (test3 > highScore) highScore = test3;
    return highScore;
}

public String toString(){
    String str;
    str =   "Name:      " + name    + "\n" +    //\n makes a newline
            "Test 1:    " + test1   + "\n" +
            "Test 2:    " + test2   + "\n" +
            "Test 3:    " + test3   + "\n" +
            "Average:   " + getAverage();
    return str;
}
}

2 个答案:

答案 0 :(得分:0)

您可以使用db4o来保存数据。它是一个使用spimple api的对象数据库。您可以存储java对象读取或删除它们。

在此处下载DB4O

并使用本教程的片段(GER):Tutorial in German

以下是一个例子:

Projectstructure

和代码:

package db4o.example;


public class Student {

    String name;

    public Student(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student Name: " + name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


package db4o.example;

import java.util.List;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;

public class Main {

    public static void main(String[] args) {
        ObjectContainer db = Db4oEmbedded.openFile("F:\\studentDB");
        saveExample(db);
        readAllExample(db);
        readExample(db);
        deleteAllExample(db);
        db.close();
    }

    private static void deleteAllExample(ObjectContainer db) {
        System.out.println("DeleteAllExample Example:");
        List<Student> allStudents =readAllExample(db);
        for (Student student : allStudents) {
            db.delete(student);
        }
        db.commit();
    }

    private static List<Student> readAllExample(ObjectContainer db) {
        System.out.println("ReadAllExample Example:");
        List<Student> allStudents = db.query(Student.class);
        System.out.println("Count: " + allStudents.size());
        for (Student student : allStudents) {
            System.out.println(student);
        }
        return allStudents;
    }

    private static void readExample(ObjectContainer db) {
        System.out.println("ReadExample Example:");
        Student queryStudent = new Student("Max Mustermann");
        // Gets all Students named Max Mustermann
        List<Student> students = db.queryByExample(queryStudent);
        System.out.println("Count: " + students.size());
        for (Student student : students) {
            System.out.println(student);
        }
    }

    private static void saveExample(ObjectContainer db) {
        System.out.println("Save Example:");
        Student myStudent = new Student("Max Mustermann");
        db.store(myStudent);
        db.commit();
    }

}

答案 1 :(得分:0)

如果您的数据不是太大或太复杂 - 您可以在过去的日子里保存在Rolodex中 - 您可以将其保存到文件中。向您的类添加方法,这些方法将正确格式化数据并将其写入给定的OutputStreamWriter或其他任何内容。还有一种方法可以读回来。

要写入该文件,请添加一个选项&#34; save&#34;在程序菜单中,选择它后,打开文件,遍历数据,并为每个对象调用保存方法。

要从文件中读取,请添加一个选项&#34; load&#34;在你的程序菜单中,当它被选中时,打开一个文件,并使用你的阅读方法为每个对象。

读取方法可以是类中的静态方法,它首先会查看文件中是否有任何数据以及是否可以正确读取它们,并且只有这样做才会创建一个对象并将其返回(否则返回null)。还有其他选项,但这是最能封装对象需求的选项。

还有一个选项可以序列化和反序列化每个对象并将其放在对象流中。

如果数据很复杂,并且有许多对象之间存在各种关系,则应使用数据库。这将需要学习一些数据库设计和SQL。

要演示文件读/写的想法,请添加到Student类:

public void save(PrintWriter outfile) {
    outfile.format("%s|%d|%d|%d%n", name, test1, test2, test3);
}

这将写一行,其中的字段用&#34; |&#34;分隔。 (竖条)。当然,您必须确保所有学生姓名中都没有垂直栏。所以你需要修改你的4参数构造函数和你的setter:

public Student(String nm, int t1, int t2, int t3) {
    name = nm.replaceAll("\\|", "");
    test1 = t1;
    test2 = t2;
    test3 = t3;
}

public void setName(String nm) {
    name = nm.replaceAll("\\|", "");
}

现在,要读取文件,我们添加一个静态方法:

public static Student load(BufferedReader infile) throws IOException {
    String line;
    line = infile.readLine();

    // Check if we reached end of file
    if (line == null) {
        return null;
    }

    // Split the fields by the "|", and check that we have no less than 4
    // fields.
    String[] fields = line.split("\\|");
    if (fields.length < 4) {
        return null;
    }

    // Parse the test scores
    int[] tests = new int[3];
    for (int i = 0; i < 3; i++) {
        try {
            tests[i] = Integer.parseInt(fields[i + 1]);
        } catch (NumberFormatException e) {
            // The field is not a number. Return null as we cannot parse
            // this line.
            return null;
        }
    }

    // All checks done, data ready, create a new student record and return
    // it
    return new Student(fields[0], tests[0], tests[1], tests[2]);
}

您可以看到这更复杂,因为您需要检查每一步都是否正常。在任何情况下,当事情不好时,我们返回null但当然,您可以决定只显示警告并阅读下一行。但是,当没有更多行时,你必须返回null。

因此,假设我们有一个List<Student> students,这就是我们将它写入文件的方式。我刚选择&#34; students.txt&#34;但您可以指定一个完整路径,指向您想要的位置。请注意我在打开新文件之前如何备份旧文件。如果出现问题,至少你有该文件的先前版本。

    File f = new File("students.txt");
    if (f.exists()) {
        File backup = new File("students.bak");
        if ( ! f.renameTo(backup) ) {
            System.err.println( "Could not create backup.");
            return;
        }
        f = new File("students.txt");
    }

    try ( PrintWriter outFile = new PrintWriter(f);) {

        for (Student student : students) {
            student.save(outFile);
        }
    } catch (FileNotFoundException e) {
        System.err.println("Could not open file for writing.");
        return;
    }

执行此操作后,如果您查找文件&#34; students.txt&#34;,您将看到您在其中写下的记录。

阅读怎么样?假设我们有一个空students列表(不是空!):

    try ( BufferedReader inFile = new BufferedReader(new FileReader(f))) {
        Student student;
        while ( ( student = Student.load(inFile)) != null) {
            students.add(student);
        }
    } catch (FileNotFoundException e) {
        System.err.println( "Could not open file for reading.");
        return;
    } catch (IOException e) {
        System.err.println( "An error occured while reading from the file.");
    }

完成此操作后,您可以检查students列表,除非文件中有错误,否则您的所有记录都将在那里。

当然,这是一个示范。您可能想要读入其他一些集合,或者不是打印错误并返回其他内容。但它应该给你这个想法。