Best way to store data for your game? (Images, maps, and such)

半世苍凉 提交于 2019-11-29 07:32:34

You can store any object as .dat file:

public class MyGame implements Serializable 
{ 
    private static void saveGame(ObjectType YourObject, String filePath) throws IOException 
    { 
        ObjectOutputStream outputStream = null; 
        try 
        { 
            outputStream = new ObjectOutputStream(new FileOutputStream(filePath)); 
            outputStream.writeObject(YourObject); 
        } 
        catch(FileNotFoundException ex) 
        { 
            ex.printStackTrace(); 
        } 
        catch(IOException ex) 
        { 
            ex.printStackTrace(); 
        } 
        finally 
        { 
            try 
            { 
                if(outputStream != null) 
                { 
                    outputStream.flush(); 
                    outputStream.close(); 
                } 
            } 
            catch(IOException ex) 
            { 
                ex.printStackTrace(); 
            } 
        } 
    } 

    public static ObjectType loadGame(String filePath) throws IOException 
    { 
        try 
        { 
            FileInputStream fileIn = new FileInputStream(filePath); 
            ObjectInputStream in = new ObjectInputStream(fileIn); 
            return (ObjectType) in.readObject(); 
        } 
        catch(FileNotFoundException ex) 
        { 
            ex.printStackTrace(); 
        } 
        catch(IOException ex) 
        { 
            ex.printStackTrace(); 
        } 
    } 
}

I don't think that zip is the wrong way. It is a rather good way. Just put everything in a jar-File. You will even be able to use a classloader to load it.

For pragmatic reasons, I would recommend using multiple files but putting them all in a subdirectory in temp.

But if part of your learning exercise is related to this topic, here are my suggestions:

First, stay away from any format like ZIP, where there is a heavy penalty for deleting, updating, adding, jumping. Even with the index files of a JAR, they are poor for anything other than compression.

So you can read up on file systems. Essentially, you are writing a file system where the 'disk' is just a binary file. That should give you a high level idea of allocation tables, etc. In order to implement such a design, you need read/write access to the underlying file; look at java.io.RandomAccessFile

Finally, if you are willing to use Java7, you can play with the new filesystem SPIs.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!