有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

  1. # 1 楼答案

    可以使用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();
        }
    
    }
    
  2. # 2 楼答案

    如果你的数据不是太大或太复杂,你可以将它保存到一个文件中,而这些数据在几天之后就可以保存在Rolodex中。向类中添加方法,这些方法将正确格式化数据,并将其写入给定的OutputStreamWriter或任何内容。还有一种方法可以读回它

    要写入文件,请在程序菜单中添加一个选项“save”,选择该选项后,打开一个文件,遍历数据,并为每个对象调用save方法

    要读取文件,请在程序菜单中添加“加载”选项,选择后打开一个文件,并使用读取每个对象的方法

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

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

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

    要演示文件读/写的想法,请在Student类中添加以下内容:

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

    这将写入一行,字段之间用“|”(垂直条)分隔。当然,你必须确保所有学生的名字都没有竖线。因此,您需要修改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,下面是我们如何将其写入文件。我只是选择了“students.txt”,但你可以指定一个完整的路径指向你想要的地方。请注意,在打开新文件之前,我是如何备份旧文件的。如果出现问题,至少你有以前版本的文件

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

    完成此操作后,如果您查找文件“students.txt”,您将看到您在其中写入的记录

    读一下怎么样?假设我们有一个空的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列表,除非文件中有错误,否则您的所有记录都会在那里

    当然,这是一个演示。您可能希望读入其他集合,或者不打印错误并返回,而是执行其他操作。但它应该给你一个想法