0
現在我有一個二進制文件,它充滿了5組問題,答案和點值。我需要從二進制文件中挑選一個隨機問題及其匹配答案和分值,並將其打印出來。我怎麼去做這件事,因爲與二進制文件,我不認爲我可以只使用nextLine()
等等。任何幫助表示讚賞,謝謝!從二進制文件中讀取和打印一個隨機元素
import java.io.*;
public class Trivia implements Serializable {
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) {
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("Who is the richest person in the US");
t[1].setAnswer("You");
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);
}
}
ArrayList<Trivia> triviaQuestions = new ArrayList<Trivia>(5);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("trivia.dat"));
triviaQuestions.add((Trivia) ois.readObject()); // This should be repeated (looped) until all questions are read
}
下面是二進制文件的截圖: http://imgur.com/a/zask2
你是什麼意思的名單做? – ProgrammingGuy123
例如,ArrayList:https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html – masinger
啊,好的。這就是我所傾向的。我怎麼會從文件中的信息拉到數組列表?因爲該文件中的信息只是二進制jibberish – ProgrammingGuy123