简体   繁体   中英

How do I store information from methods to be used in another session?

So I'm making a program that will store the meetings I've had with some kids I'm tutoring. It'll keep tabs on the meeting times, discussions, and how many hours I've done. I know how to write all the methods to do that, but my issue is that the program will only hold that information for the session that the program is open... how would I go about storing this information and accessing it after the program is closed and opened again?

This is some excerpts from a test score keeper program I did in java class that has this same issue...

    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;
}
}

You could use db4o for persisting your data. Its an object-database with a spimple api to use. You can store java object read or delete them..

Download it here DB4O

And use the snippets of this tutorial (GER): Tutorial in German

Here is an example:

项目结构

and Code:

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();
    }

}

If your data is not too big or complicated - something that you could save in a Rolodex in days gone by - you can save it to a file. Add methods to your class that will format the data properly and write it to a given OutputStream or Writer or whatever. And a method that will read it back.

To write to the file, add an option "save" in your program menu, and when it's chosen, open a file, iterate through your data, and call the saving method for each of your object.

To read from the file, add an option "load" in your program menu, and when it's chosen, open a file, and use your method of reading for each object.

The method for reading can be a static method in the class, that will first see if there are any data in the file and if it can read them properly, and only if it did, will create an object and return it (otherwise return null). There are other options, but this is the one that most encapsulates the needs of the object.

There is also an option to serialize and deserialize each object and put it in an object stream.

If the data is complicated, and there are many objects with various relations between them, you should use a database. This will require learning some database design and SQL.

To demonstrate the file reading/writing idea, add to your Student class:

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

This will write a line with the fields separated by "|" (vertical bar). Of course, you'll have to make sure none of the student names has a vertical bar in it. So you'll need to modify your 4-parameter constructor and your 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("\\|", "");
}

Now, to read the file, we add a static method:

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]);
}

You can see that this is more complicated, because you need to check that everything is OK at every step. In any case when things are not OK, we return null but of course, you can decide to just display a warning and read the next line. You'll have to return null when there are no more lines, though.

So, assuming we have a List<Student> students , here is how we write it to a file. I just chose "students.txt" but you can specify a full path leading where you want it. Note how I'm making a backup of the old file before I open the new file. If something goes wrong, at least you have the previous version of the file.

    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;
    }

After you do this, if you look for the file "students.txt", you will see the records you wrote in it.

How about reading it? Assume we have an empty students list (not null!):

    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.");
    }

Having done this, you can check your students list, and unless there were errors in the file, all your records will be there.

This is a demonstration, of course. You may want to read into some other collection or instead of printing an error and returning do something else. But it should give you the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM