简体   繁体   中英

Store java arrays to file for read and write

I am fairly new to StackOverflow so I'm sorry if this question is not written correctly.

I'm currently learning java and I'm looking for a way to store a set of arrays as a file so that changes to the array will persist between different instances of the program. I would need to read an write any changes to the best times list to a file.

I have done some research into storing arrays but most of what I've read seems to only store a simple array of strings, integers, ect. These arrays are a little bit more complex so I'm not sure how to do it. I don't expect anyone to write all of my code for me but I could use some help on knowing where to start.

This is the sample data that would need to be stored. These are best times for a java game.

Are there methods to store this kind of data in a file of some sort?

public class BestTimes 
    {
        BestTimes[] beginner = new BestTimes[10];
        BestTimes[] intermediate = new BestTimes[10];
        BestTimes[] expert = new BestTimes[10];

        public BestTimes() {
        beginner[0] = new BestTimes(1, "John", 10.5);
        beginner[1] = new BestTimes(2, "James", 20.3);
        beginner[2] = new BestTimes(3, "Jill", 30);
        beginner[3] = new BestTimes(4, "Bill", 35);
        beginner[4] = new BestTimes(5, "Kevin", 40);
        beginner[5] = new BestTimes(6, "Nate", 55);
        beginner[6] = new BestTimes(7, "Bob", 75);
        beginner[7] = new BestTimes(8, "Dan", 85);
        beginner[8] = new BestTimes(9, "Amy", 93);
        beginner[9] = new BestTimes(10, "Jane", 100);

        intermediate[0] = new BestTimes(1, "John", 110.5);
        intermediate[1] = new BestTimes(2, "James", 120.3);
        intermediate[2] = new BestTimes(3, "Jill", 130);
        intermediate[3] = new BestTimes(4, "Bill", 135);
        intermediate[4] = new BestTimes(5, "Kevin", 140);
        intermediate[5] = new BestTimes(6, "Nate", 155);
        intermediate[6] = new BestTimes(7, "Bob", 175);
        intermediate[7] = new BestTimes(8, "Dan", 185);
        intermediate[8] = new BestTimes(9, "Amy", 193);
        intermediate[9] = new BestTimes(10, "Jane", 200);

        expert[0] = new BestTimes(1, "John", 210.5);
        expert[1] = new BestTimes(2, "James", 220.3);
        expert[2] = new BestTimes(3, "Jill", 230);
        expert[3] = new BestTimes(4, "Bill", 235);
        expert[4] = new BestTimes(5, "Kevin", 240);
        expert[5] = new BestTimes(6, "Nate", 255);
        expert[6] = new BestTimes(7, "Bob", 275);
        expert[7] = new BestTimes(8, "Dan", 285);
        expert[8] = new BestTimes(9, "Amy", 293);
        expert[9] = new BestTimes(10, "Jane", 300);
        }

    public int ranking;
    public String playerName;
    public double time;

    public BestTimes(int r, String p, double t) 
    {
        ranking = r;
        playerName = p;
        time = t;
    }
}

In order to store an object (datastructure), you need to serialize it: convert it to an stream of bytes, characters, whatever.

There exist multiple ways to serialize an object ranging from JSON over XML to the object serializer/deserializer .

For instance (as specified in the webpage):

First you must add implements Serializable at the end of the class definition, so:

public class BestTimes implements Serializable {

Then you can serialize using:

try(FileOutputStream f = new FileOutputStream("file.txt");
    ObjectOutput s = new ObjectOutputStream(f)) {
    s.writeObject(beginner);
    s.writeObject(intermediate);
    s.writeObject(expert);
}

And later read it as:

BestTimes[] beginner, intermediate, expert;
try(FileInputStream in = new FileInputStream("file.txt");
    ObjectInputStream s = new ObjectInputStream(in)) {
    beginner = (BestTimes[]) s.readObject();
    intermediate = (BestTimes[]) s.readObject();
    expert = (BestTimes[]) s.readObject();
}

The easy thing about the object serializer is that you don't have to define a format on your own. That's the task of the Java virtual machine, and furthermore it can encode all kinds of objects whereas JSON for instance can't handle datastructures that contain loops (example: graphs), XML can't handle loops as well and CSV is only well suited for table content.

A disadvantage however is that the datastructures are encoded binary : they cannot be read easily. Although in this case that might be an advantage since some users tend to alter the file to increase their highscores ;).

The easiest way to do this would be to serialize the arrays as JSON and store their JSON representation.

There is no reason to come up with your own solution to serializing arrays, as it is already a solved problem! The easier the better in my opinion.

As others have said using some JSON-Library to read/write your data to files is a valid option.

If you want a more pure Java approach you can model your data in classes implementing the Serializable interface and read/write them using Java's ObjectOutput- and ObjectInputStream .

I would either use a database, or export your content as CSV (comma separated values) file. You could introduce a 4th attribute the stands for the type of your data (beginner, expert etc).

1, John, 110, beginner
2, Mark, 90, professional
...

You can store in csv file too,

Code

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.csvreader.CsvWriter;

public class CsvWriterAppendExample {

public static void main(String[] args) {

    String outputFile = "users.csv";

    // before we open the file check to see if it already exists
    boolean alreadyExists = new File(outputFile).exists();

    try {
        // use FileWriter constructor that specifies open for appending
        CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');

        // if the file didn't already exist then we need to write out the header line
        if (!alreadyExists)
        {
            csvOutput.write("id");
            csvOutput.write("name");
            csvOutput.endRecord();
        }
        // else assume that the file already has the correct header line

        // write out a few records
        csvOutput.write("1");
        csvOutput.write("Bruce");
        csvOutput.endRecord();

        csvOutput.write("2");
        csvOutput.write("John");
        csvOutput.endRecord();

        csvOutput.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

   }
}

Output Format

id,name
1,Bruce
2,John

Check http://www.csvreader.com/java_csv_samples.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM