Member 13620781 Ответов: 1

Как загрузить игровые данные из файла?


Я попытался сохранить игровые данные в файл с помощью Serializable, и теперь я хочу загрузить сохраненные данные из файла в новый JFrame. На самом деле я пытаюсь сделать следующее: если игрок нажмет на кнопку Продолжить, игра начнется с того состояния, в котором она была остановлена, и будет сохранена, когда мы сыграем ее снова. Надеюсь, вы поможете мне решить эту проблему. Заранее спасибо.

Вот какие ошибки я получил:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at java.awt.Container.updateGraphicsData(Container.java:1158)
        at java.awt.Container.updateGraphicsData(Container.java:1160)
        at java.awt.Container.updateGraphicsData(Container.java:1160)
        at java.awt.Container.updateGraphicsData(Container.java:1160)
        at java.awt.Container.updateGraphicsData(Container.java:1160)
        at java.awt.Component.setGraphicsConfiguration(Component.java:1153)
        at java.awt.Window.setGraphicsConfiguration(Window.java:3177)
        at java.awt.Window.initGC(Window.java:478)
        at java.awt.Window.initDeserializedWindow(Window.java:2987)
        at java.awt.Window.readObject(Window.java:3075)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1158)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2176)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2067)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1571)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
        at javax.swing.event.EventListenerList.readObject(EventListenerList.java:274)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1158)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2176)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2067)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1571)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2285)
        at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:561)
        at javax.swing.JComponent.readObject(JComponent.java:5467)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1158)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2176)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2067)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1571)
        at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1973)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1565)
        at java.io.ObjectInputStream.access$800(ObjectInputStream.java:214)
        at java.io.ObjectInputStream$GetFieldImpl.readFields(ObjectInputStream.java:2450)
        at java.io.ObjectInputStream.readFields(ObjectInputStream.java:601)
        at java.awt.Container.readObject(Container.java:3720)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1158)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2176)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2067)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1571)
        at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1973)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1565)
        at java.io.ObjectInputStream.access$800(ObjectInputStream.java:214)
        at java.io.ObjectInputStream$GetFieldImpl.readFields(ObjectInputStream.java:2450)
        at java.io.ObjectInputStream.readFields(ObjectInputStream.java:601)
        at java.awt.Container.readObject(Container.java:3720)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1158)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2176)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2067)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1571)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
        at GameLogic$Main.actionPerformed(GameLogic.java:278)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
        at java.awt.Component.processMouseEvent(Component.java:6533)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
        at java.awt.Component.processEvent(Component.java:6298)
        at java.awt.Container.processEvent(Container.java:2238)
        at java.awt.Component.dispatchEventImpl(Component.java:4889)
        at java.awt.Container.dispatchEventImpl(Container.java:2296)
        at java.awt.Component.dispatchEvent(Component.java:4711)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4897)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4534)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4475)
        at java.awt.Container.dispatchEventImpl(Container.java:2282)
        at java.awt.Window.dispatchEventImpl(Window.java:2746)
        at java.awt.Component.dispatchEvent(Component.java:4711)
        at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
        at java.awt.EventQueue.access$500(EventQueue.java:97)
        at java.awt.EventQueue$3.run(EventQueue.java:709)
        at java.awt.EventQueue$3.run(EventQueue.java:703)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
        at java.awt.EventQueue$4.run(EventQueue.java:733)
        at java.awt.EventQueue$4.run(EventQueue.java:731)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)


Что я уже пробовал:

class GameLogic extends ... {
/*...
.
.
.*/

static Board board;
/*...
.
.
.*/

else if(btnTxt.equals("Save")) {
				
				try {
				FileOutputStream file = new FileOutputStream("chess.txt");
				ObjectOutputStream object = new ObjectOutputStream(file);
				object.writeObject(board);
				object.close();
			 // create a dialog Box 
			 JFrame f = new JFrame();
            JDialog d = new JDialog(f, "Chess Game"); 
  
            // create a label 
            JLabel l = new JLabel("Game is successfully saved!"); 
  
            d.add(l); 
  
            // setsize of dialog 
            d.setSize(200,100); 
			d.setLocationRelativeTo(null);
  
            // set visibility of dialog 
            d.setVisible(true); 

			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}


		} // close save
		else if(btnTxt.equals("Continue"))
		{
			JFrame fr1 = new JFrame();
			try {
		FileInputStream fileInputStream = new FileInputStream("chess.txt");
		BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
		ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream);
		Board object = (Board)objectInputStream.readObject();
		objectInputStream.close();
		} catch(IOException fe)
		{
			fe.printStackTrace();
		} catch(ClassNotFoundException ce)
		{
			ce.printStackTrace();
		}
		} // close continue

1 Ответов

Рейтинг:
1

Richard MacCutchan

Это та же проблема, что и ваш предыдущий вопрос на эту тему. В разделе продолжить Вы делаете это:

Board object = (Board)objectInputStream.readObject();

Поэтому, как только вы выходите из этой процедуры, этот объект выходит из области видимости и выбрасывается. Перейдите к справочнику Java и узнайте о области действия и времени жизни объектов.

Кроме того, не используйте зарезервированные имена, такие как объект для ваших переменных.