存储游戏数据的最佳方式?(图像,地图等)

Fel*_*mbc 5 java storage

我正在创建一个基本的2D游戏(以及一个游戏引擎),我目前正在为我的数据开发文件格式.当然,对于这个游戏来说,我需要缓存.我发现将游戏的所有数据保留在一个文件中并不是非常不专业(不一定,只要文件是某种缓存格式).

所以这就是我来这里问的原因.我正在考虑做一个zip文件,但我觉得这根本不是最好的方式.我还在考虑做另一个二进制写入器,它将具有标题(文件类型,"位置")和每个文件的封闭标记,因此很容易解释.但我觉得这样效率太低了.

那么请你有什么想法吗?

注意:此游戏引擎仅用于学习目的.

tl; dr我需要一种有效的方法来存储我正在制作的游戏中的图像等数据.

Eng*_*uad 7

您可以将任何对象存储为.dat文件:

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(); 
        } 
    } 
}
Run Code Online (Sandbox Code Playgroud)