java - 读取/写入二进制文件

标签 java file binary

现在我必须将对象数组读/写到二进制文件中。我已经编写了代码,但由于某种原因,我收到了写入错误(我在 try catch 中创建的错误)。任何有关如何解决此问题的解决方案都将受到赞赏。谢谢。

public class Trivia {
private String question;
private String answer;
private int points;

public Trivia() {
    question = " ";
    answer = " ";
    points = 0;
}

public String getQuestion() {
    return question;
}

public String getAnswer() {
    return answer;
}

public int getPoints() {
    return points;
}

public void setQuestion(String q) {
    question = q;
}

public void setAnswer(String a) {
    answer = a;
}

public void setPoints(int p) {
    points = p;
}

}

import java.io.*;
import java.util.*;

public class Driver  {

public static void main(String[] args) {
    String fileName = "trivia.dat";
    Trivia[] t = new Trivia[5];
    for (int i = 0; i < 5; i++) {
        t[i] = new Trivia();
    }

    t[0].setQuestion("How many states are in the US?");
    t[0].setAnswer("50");
    t[0].setPoints(1);

    t[1].setQuestion("What is the capital of Michigan?");
    t[1].setAnswer("Lansing");
    t[1].setPoints(1);

    t[2].setQuestion("How many senators come from each state?");
    t[2].setAnswer("2");
    t[2].setPoints(2);

    t[3].setQuestion("What is the largest state?");
    t[3].setAnswer("Alaska");
    t[3].setPoints(2);

    t[4].setQuestion("Who was the thrid president?");
    t[4].setAnswer("Thomas Jefferson");
    t[4].setPoints(3);

    ObjectOutputStream outputStream = null;

    try{
        outputStream = new ObjectOutputStream(new FileOutputStream("trivia.dat"));

    }catch(IOException e){
        System.out.println("Could not open file");
        System.exit(0);
    }

    try{
        outputStream.writeObject(t);
        outputStream.close();
    }catch(IOException e){
        System.out.println("Writing error");
        System.exit(0);
    }

    ObjectInputStream inputStream = null;

    try{
        inputStream = new ObjectInputStream(new FileInputStream("trivia.dat"));

    }catch(IOException e){
        System.out.println("File not found.");
        System.exit(0);
    }
     Trivia[] test = null;

     try{
         test = (Trivia[])inputStream.readObject();
     }catch(Exception e){
         System.out.println("Reading error");
         System.exit(0);
     }



}
}

最佳答案

您的 Trivia 类必须实现 Serialized 接口(interface),以允许使用 ObjectInputStream 编写它。

关于java - 读取/写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35735354/

相关文章:

json - 使用 jq 将数字字节值数组转换为字符串

java - 如何为 jframe 设置标题?

java - 如何从MySQL数据库获取数据到android

java - 控制Lucene中文档的磁盘位置

java - 如何使用 Java 移动文件

python - 为什么我将四个字节转换为二进制只有 30 个二进制数字?

replace - 为什么 sed 无法替换二进制文件中的 0x24 字节?

java - NoSQL 无模式数据和静态类型语言

python - Django动态文件上传路径

java - 在目录中创建文件之前检查目录中的写访问权限