MAG
MAG

Reputation: 474

how can I save variable in a file?

is there a way I can save a variable for example an array of colors and then retrieve it. Im making a board game and i need to be able to save at any given time. If it doesn't work like that, can any give me any other recommendation in what can I use?.

Upvotes: 0

Views: 168

Answers (3)

Andrew Thompson
Andrew Thompson

Reputation: 168825

There are a multitude of ways to serialize data. Here is one (lifted from a small project I have open), using ArrayList as the data container, XMLEncoder/XMLDecoder for serialization, and puts them in a Zip for good measure.

public void loadComments() throws FileNotFoundException, IOException {
    File f = getPropertiesFile();
    FileInputStream fis = new FileInputStream(f);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry entry = zis.getNextEntry();

    while (!entry.getName().equals(COMMENTS_ENTRY_NAME)) {
        entry = zis.getNextEntry();
    }
    InputSource is = new InputSource(zis);
    XMLDecoder xmld = new XMLDecoder(is);
    comments = (ArrayList<Comment>) xmld.readObject();
    try {
        fis.close();
    } catch (IOException ex) {
        Logger.getLogger(CommentAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public void saveComments() throws FileNotFoundException, IOException {
    CommentComparator commentComparator = new CommentComparator();
    Collections.sort(comments, commentComparator);

    File f = getPropertiesFile();
    System.out.println("Save to: " + f.getAbsolutePath());
    File p = f.getParentFile();
    if (!p.exists() && !p.mkdirs()) {
        throw new UnsupportedOperationException(
                "Could not create settings directory: "
                + p.getAbsolutePath());
    }
    FileOutputStream fos = new FileOutputStream(f);
    ZipOutputStream zos = new ZipOutputStream(fos);

    ZipEntry entry = new ZipEntry(COMMENTS_ENTRY_NAME);
    zos.putNextEntry(entry);

    XMLEncoder xmld = new XMLEncoder(zos);
    xmld.writeObject(comments);
    xmld.flush();
    xmld.close();
}

Upvotes: 1

Curt
Curt

Reputation: 5722

Look at the XML serialization utilities. If your "variable" is a class instance (or contained in one), this should make saving the values quite simple.

If it's not, you'll have to figure out a way to write out the variable's values, and parse it back, from a string so that you can save it to a text file.

Upvotes: 2

Michael Lang
Michael Lang

Reputation: 3992

You can use an ObjectOutputStream to write objects which implement the Serializable interface.

FileOutputStream fos = new FileOutputStream("my.save");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(colorsArray);

Of course, loading is also possible in the same way:

FileInputStream fis = new FileInputStream("my.save");
ObjectInputStream ois = new ObjectInputStream(fis);
colorsArray = (Color[]) ois.readObject();

Upvotes: 2

Related Questions