Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

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

I'm creating a basic 2D game (well a game engine) and I've currently been developing the file formats for my data. Of course, for this game to run, I will need cache. I find it quite unprofessional to leave all the data for the game to not be in a single file (well not necessarily, as long as the files are in a cache format of some kind).

So that's why I've came here to ask. I was thinking of doing a zip file but I feel like that isn't the best way at all. I was also thinking of doing another binary writer which will have headers (type of file, "location") and an enclosing tag for each of the files so it would be easy to interpret. But I felt like that was too inefficient.

So please, do you have any ideas?

Note: This game engine is really just for learning purposes.

tl;dr I need an efficient way to store data such as images for my game I'm making.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(); 
        } 
    } 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...