抱歉,如果这是一个简单的问题,但我是Java编程的新手,无法处理Java Save File Bug的一个问题。错误是,有时它会保存并加载值而不会出错,有时候它显示错误并仍然加载。但有时savefile不会工作。
我得到的错误:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Clicker.ClickerGame.LoadFile(ClickerGame.java:2479)
at Clicker.mainClass.main(mainClass.java:27)
我的主要(入门级):
package Clicker;
import javax.swing.JFrame;
public class mainClass {
public static void main(String[] args) {
ClickerGame CG = new ClickerGame();
JFrame frame = new JFrame("CarCollectionarV1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CG.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
frame.setSize(1000, 700);
CG.LoadFile();
boolean GameLoop = true;
while(GameLoop){
CG.refresh();
CG.SaveFile();
}
}
}
ClickerGame类(SaveFile和LoadFile函数在哪里):
public void SaveFile(){
try{
File SaveFile = new File("SaveFile.sav");
if(!SaveFile.exists()) {
SaveFile.createNewFile();
}
FileOutputStream saveFileSub = new FileOutputStream(SaveFile);
ObjectOutputStream save = new ObjectOutputStream(saveFileSub);
save.writeObject(CarMain.main);
save.writeObject(Box.boxes);
save.writeObject(CarFrame.frames);
save.writeObject(Part.parts);
save.writeObject(CarsLv1.cars);
save.writeObject(CarsLv2.cars);
save.writeObject(CarsLv3.cars);
save.writeObject(CarsLv4.cars);
save.writeObject(CarsLv5.cars);
save.writeObject(CarsLv6.cars);
save.writeObject(CarsLv7.cars);
save.writeObject(CarsLv8.cars);
save.writeObject(CarsLv9.cars);
save.writeObject(CarsLv10.cars);
save.close();
}
catch(Exception exc){
exc.printStackTrace();
}
}
public void LoadFile(){
try{
File SaveFile = new File("SaveFile.sav");
if(!SaveFile.exists()) {
SaveFile.createNewFile();
}
FileInputStream SaveFileSub = new FileInputStream(SaveFile);
ObjectInputStream load = new ObjectInputStream(SaveFileSub);
CarMain.main = (Integer[]) load.readObject();
Box.boxes = (Integer[]) load.readObject();
CarFrame.frames = (Integer[]) load.readObject();
Part.parts = (Integer[]) load.readObject();
CarsLv1.cars = (String[]) load.readObject();
CarsLv2.cars = (String[]) load.readObject();
CarsLv3.cars = (String[]) load.readObject();
CarsLv4.cars = (String[]) load.readObject();
CarsLv5.cars = (String[]) load.readObject();
CarsLv6.cars = (String[]) load.readObject();
CarsLv7.cars = (String[]) load.readObject();
CarsLv8.cars = (String[]) load.readObject();
CarsLv9.cars = (String[]) load.readObject();
CarsLv10.cars = (String[]) load.readObject();
load.close();
}
catch(Exception exc){
exc.printStackTrace();
}
}
答案 0 :(得分:2)
你的loadFile方法读取的内容多于文件内容。这就是EOFException(文件结束异常)的含义。
在您可以看到行号的IDE中,您将能够确切地告诉您过度读取的位置:它在ClickerGame类中的第2479行(请参阅错误的堆栈跟踪)
如果我猜测,你在保存之前加载文件:因为你的loadfile创建了文件,如果文件不存在,你将创建一个空文件然后你尝试阅读。