0

I want to store some integers and arrays into a file so i can let my program read and use them, but I have no idea how to do this. I know that I can read single integers with a Scanner and save them to an array by iteration, but I would like to have a file like

Number=5;
Array={1, 2, 3, 4, 5};

And my program should assign the numbers to it's variables automatically, like

int Number = file.get(Number);
int[] Array = file.get(Array);

Is there some way to accomplish this?

Thank you in advance

vicco
  • 1,049
  • 2
  • 14
  • 33
  • 1
    There are plenty ways to do it, depending on how the data is stored in the file: binary data, plain text, from a specific format like XML or JSON... – Luiggi Mendoza Jan 05 '15 at 20:10
  • Store it in a more structured format & use a library. – kittylyst Jan 05 '15 at 20:12
  • Regardless of what you use, you will have to write some part of the function `file.get` yourself. The closest thing to "automatic" you will get is probably JSON or some binary encoding. – merlin2011 Jan 05 '15 at 20:12
  • Yes, I have already read about JSON, XML and Property files, but I did not really understand how to do what I want with them. – vicco Jan 05 '15 at 20:14
  • Start with Java Properties, write several test programs as simple as possible, each one doing the single thing. Repeat until you have better understanding. There's no other way. – Victor Sorokin Jan 05 '15 at 20:16
  • possible duplicate of [How to Create JSON Array in Java](http://stackoverflow.com/questions/7976643/how-to-create-json-array-in-java) – merlin2011 Jan 05 '15 at 20:20

1 Answers1

0

The easiest way to do this is by using serialization. To store your information in a file, use a FileOutputStream and an ObjectOutputStream (from the java.io package), like this:

File saveFile = new File("filename.sav");
try {
    FileOutputStream fileOut = new FileOutputStream(saveFile);
    try (ObjectOutputStream objOut = new ObjectOutputStream(fileOut)) {
        objOut.writeObject(number); // you should use lower case for variable names
        objOut.writeObject(array);
    }
} catch (IOException e) {
}

This will store your information in a binary file named "filename.sav". To get your integer and array from that file, use a FileInputStream and an ObjectInputStream and cast the retrieved objects to the desired type in the order they were stored in:

try {
    FileInputStream fileIn = new FileInputStream("filename.sav");
    try (ObjectInputStream objIn = new ObjectInputStream(fileIn)) {
        int number = (int) objIn.readObject();
        int[] array = (int[]) objIn.readObject();
    }
} catch (IOException | ClassNotFoundException e) {
}

This will also work for any serializable object (an object that implements Serializable).

Santiago Benoit
  • 994
  • 1
  • 8
  • 22