сейчас я должен читать/записывать массив объектов в двоичный файл. У меня есть код на месте, но по какой-то причине я получаю ошибку записи (ошибка, которую я создал в моем 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);
}
}
}
И исключение ...? – fge
Покажите нам трассировку стека –
Я сказал это выше. Я получаю сообщение «Ошибка написания». Это уже в коде 'catch (IOException e) { System.out.println (« Ошибка написания »); System.exit (0); } ' – ProgrammingGuy123