【问题标题】:EOFException Reading UTF from Binary file, Student DatabaseEOFException 从二进制文件、学生数据库中读取 UTF
【发布时间】:2016-11-08 03:25:59
【问题描述】:

我在从学生数据库问题中读取二进制值时遇到了很多麻烦。经过一些修补后,我得到了输出以正常工作并以我想要的格式,即(int id,String name,int age)但是,我在从我的文件中加载编码的二进制数据值时遇到了很多麻烦。根据编译器,它一直读取到 UT​​F 值,然后我收到 EOFException。

这是我试图解决的问题:

首先,启动程序后,用户选择以下任一选项 1. 将学生添加到数据库 2. 从数据库中删除一个学生 3.打印数据库中的特定学生 4. 打印数据库中的所有学生

如果他们选择,用户会将 Student obj 添加到学生向量中。 学生 obj 包含一个 ID(int)、一个 Name(String) 和一个 age(int)。

移除一个学生会根据用户输入的 ID 号从向量中移除他们。

选项 3/4 将学生 obj(s) 打印到屏幕上(而不是二进制文件)

用户输入5退出程序后;向量中的学生 obj 被写入二进制文件。

当程序重新运行时,它会将学生 obj 重新加载到向量中。 (记住文件是从二进制文件写入和加载的)

我遇到的问题是,当我尝试加载文件“Student.data”(我当前正在写入的文件)时它一直在第 198 行向我抛出 EOFException读学生的名字。

我认为问题可能出在我编写代码时,但我修改了获取名称值并多次写入它们的方式,但仍然无法正确加载它们。

关于如何解决此问题的任何建议?

代码:

//StudentDB.java
import java.util.Vector;
import java.io.*;
import java.util.Scanner;
class Student
{
    private int id;
    private String name;
    private int age;
    //Desc: Initializes the student to id=0, name="none", and age=0
    public Student()
    {
        this.id=0;
        this.name="none";
        this.age=0;
    }
    //Desc: Initializes the student to id=i, name=n, age=a
    public Student(int I, String n, int a)
    {
        this.id=I;
        this.name=n;
        this.age=a;
    }
    //Desc: Sets the current id to s
    public void setID(int s)
    {
        this.id=s;
    }
    //Return: The current ID value
    public int getID()
    {
        return this.id;
    }
    //Desc: sets the current name of the student to s
    public void setName(String s)
    {
        this.name=s;
    }
    //Return: The current name of the student
    public String getName()
    {
        return this.name;
    }
    //Desc: sets the current age of the obj to a
    public void setAge(int a)
    {
        this.age=a;
    }
    //Return: The students current age
    public int getAge()
    {
        return this.age;
    }
    //Return: True if id of this student equals id of obj, false otherwise
    public boolean equals(Object obj)
    {
        Student stu= (Student)obj;
        if(this.id==stu.id) return true;
        else return false;
    }
    //Desc: Compares two students based on their ID to determine if they're
    // the same
    //Return: 1  if the current Student's ID is greater than stu
    //      0 if the students ID's are the same
    //      -1 if Student stu's ID is larger
    public int compareTo(Student stu)
    {
        if(this.id> stu.id) return 1;

        else if(this.id==stu.id) return 0;

        else return -1;

    }
    //Return: id+"Name"+age
    public String toString()
    {
            return (this.getID()+ " "+this.getName()+" "+this.getAge());
    }
}
public class StudentDB
{
    private static Scanner keyboard=new Scanner(System.in);
    //Desc: Maintains a database of Student Records. The database is stored in
    // a binary file called "Student.data"
    //Input: User enters commands from keyboard to manipulate database
    //Output: Database updated as directed by user.
    public static void main(String[]args) throws IOException
    {
        Vector<Student> v= new Vector<Student>();
        File s= new File("Student.data");
        if(s.exists()) loadStudent(v);
        int choice=5;
        do
        {
            System.out.println("\t1. Add a Student Record");
            System.out.println("\t2. Remove a Student Record");
            System.out.println("\t3. Print a Student Record");
            System.out.println("\t4. Print all Student Records");
            System.out.println("\t5. Quit");
            choice= keyboard.nextInt();
            keyboard.nextLine();
            switch(choice)
            {
                case 1: addStudent(v); break;
                case 2: removeStudent(v); break;
                case 3: printStudent(v); break;
                case 4: printAllStudent(v); break;
                default: break;
            }
        } while(choice!=5);
        storeStudent(v);
    }
    //Input: user enters an integer(id), a string(name), an integer(age) from
    //the keyboard all on seperate lines
    //Post: The input record added to v if id does not exist
    //Output: various prompts as well as "Student Added" or "Add failed:
    // Student already exists" printed on the screen accordingly
    public static void addStudent(Vector<Student> v)
    {
        Student stu= new Student();

        System.out.print("Please enter a Student ID:");
        stu.setID(keyboard.nextInt());
        keyboard.nextLine();

        System.out.print("Please enter a Student Name:");
        stu.setName(keyboard.nextLine());

        System.out.print("Please enter a Student Age:");
        stu.setAge(keyboard.nextInt());
        keyboard.nextLine();

        int index= v.indexOf(stu);
        if(index==-1)
        {
            v.add(stu);
            System.out.println("Student Added");
        }
        else System.out.println("Add failed: Student already exists");

    }
    //Input: user enters an integer(id) from the Keyboard
    //Post: The records in v whose id field matches the input removed from v
    //Output: various prompts as well as "Student removed" or "Remove failed:
    // Student does not exsist" printed on the screen accordingly
    public static void removeStudent(Vector<Student>v)
    {
        System.out.print("Student ID:");
        int id= keyboard.nextInt();
        Student stu= new Student(id,"",99);
        if(v.remove(stu))   System.out.println("Student Removed");
        else System.out.println("Remove Failed");
    }
    //Input: user enters an integer(id) from the Keyboard
    //Output: various prompts as well as the record in v whose id field 
    // matches the input printed on the screen or "Print failed: Student
    // does not exsist" printed on the screen accordingly
    public static void printStudent(Vector<Student>v)
    {
        System.out.print("Student ID:");
        int id= keyboard.nextInt();
        Student stu= new Student(id,"",99);
        int index=v.indexOf(stu);
        if(index!=-1)
        {
            System.out.println(v.get(index).toString());
        }
        else System.out.println("Print failed: Student does not exsist!");
    }
    //Output: All records in v printed on the screen 
    public static void printAllStudent(Vector<Student>v)
    {
        Student stu=new Student();
        for(int i=0; i<v.size();++i)
        {
            stu=v.get(i);
            System.out.println(stu);
        }

    }
    //Input: Binary file Student.data must exist and contains student records
    //Post: All records in Student.data loaded into vector v.
    public static void loadStudent(Vector<Student>v)throws IOException
    {
        Student stu;
        int c;
        DataInputStream f= new DataInputStream(
                new FileInputStream("Student.data"));
       try {
           while(true)
           {
               stu=new Student();
               int id=f.readInt();
               stu.setID(id);
               String name= f.readUTF();
               stu.setName(name);
               int age= f.readInt();
               stu.setAge(age);
               v.add(stu);
           }
       }
       catch(EOFException e)
       {
           System.out.println("Error!: End of File Exception");
           f.close();
       }
       catch(IOException e)
       {
           System.out.println("Error Reading File");
           f.close();
           System.exit(1);
       }
        f.close();
    }
    //Output: All records in v written to binary file Student.data
    public static void storeStudent(Vector<Student>v) throws IOException
    {
        Student stu= new Student();
        DataOutputStream s= new DataOutputStream(
                new FileOutputStream("Student.data"));
        for(int i=0; i<v.size(); ++i)
        {
            stu=v.get(i);
            s.writeInt(stu.getID());
            s.writeUTF(stu.getName());
            s.writeInt(stu.getAge());
        }
        s.close();
    }
}

【问题讨论】:

  • 编辑您的姓名和电子邮件,哈哈。还提供示例用法。遇到错误的main 方法。
  • 因为文件里有随机的垃圾字符,看一下十六进制编辑器自己看看。您不必删除学生即可导致错误。您所要做的就是添加一个学生。意味着你的写操作很糟糕。

标签: java database utf-8 binary binaryfiles


【解决方案1】:

两个原因是它坏了。

  1. 你有无限的阅读量
  2. 您将每个学生都附加到同一行

进行以下更改

loadStudentwhite(true) 更改为while(f.available() &gt; 0) 并在末尾添加f.readChar();

public static void loadStudent(Vector<Student>v)throws IOException
{
    Student stu;
    int c;
    DataInputStream f= new DataInputStream(
            new FileInputStream("Student.data"));
   try {
       // CHANGE HERE IS IMPORTANT
       while(f.available() > 0)
       {
           stu=new Student();
           int id=f.readInt();

           stu.setID(id);
           String name= f.readUTF();
           stu.setName(name);
           int age= f.readInt();
           stu.setAge(age);
           v.add(stu);
           // This read char is important since it's one user per line.
           f.readChar();
       }
   }
   catch(EOFException e)
   {
       System.out.println("Error!: End of File Exception");
       f.close();
   }
   catch(IOException e)
   {
       System.out.println("Error Reading File");
       f.close();
       System.exit(1);
   }
    f.close();
}

storeStudent 保存学生时,在末尾添加一个换行符。 s.writeChar('\n');

public static void storeStudent(Vector<Student>v) throws IOException
{
    Student stu= new Student();
    DataOutputStream s= new DataOutputStream(
            new FileOutputStream("Student.data"));
    for(int i=0; i<v.size(); ++i)
    {
        stu=v.get(i);
        s.writeInt(stu.getID());
        s.writeUTF(stu.getName());
        s.writeInt(stu.getAge());
        // One user per line
        s.writeChar('\n');
        }
    s.close();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2015-04-23
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 2023-03-19
    相关资源
    最近更新 更多