-1

I am trying to get a keychaincount and name and put it in an array. I then want to add this array to a temporary file to save the variables for the next time I run the code. I have this code so far:

public static void order_history(){
    String[][] newArray = {{name, String.valueOf(keychain_count)}};
    try {
        FileOutputStream fos = new FileOutputStream("t.tmp");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(newArray);
        oos.close();
    } catch (IOException i) {
        i.printStackTrace();
    }

I basically want to be able to read the file and get all the arrays to parse through them.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
VS Puzzler
  • 21
  • 5
  • Does this answer your question? [storing an array in a file in java](/q/1503424/90527), [how to write an array to a file Java](/q/13707223/90527) – outis Nov 01 '22 at 13:24

1 Answers1

1

To load array from file use these input streams:

String[][] loaded = null;
try {
    FileInputStream fis = new FileInputStream("t.tmp");
    ObjectInputStream ois = new ObjectInputStream(fis);
    loaded = (String[][]) ois.readObject();
    ois.close();
} catch (IOException i) {
    i.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

Don't forget to check that the array is loaded successfully:

if (loaded == null) {
    // save file is corrupted, you need to create a new data from scratch
}
Mishin870
  • 125
  • 6
  • Is the data from the file saved in the variable loaded? When I print out loaded, I get this value: "[[Ljava.lang.String;@5a2e4553" – VS Puzzler Oct 30 '22 at 22:21
  • 1
    @VSPuzzler, your code is using a two-dimensional array of strings to store your data. Therefore to get, for example, "name" you need to write: `loaded[0][0]` (based on your code in question). If you want to print the whole array, use this: `System.out.println(Arrays.deepToString(loaded));`. By the way, ObjectStreams support any objects (except primitive types like int, char, ...), so you can encode your data in your custom class variable. If my answer was helpful and solves your question, then accept it, thanks :) – Mishin870 Oct 31 '22 at 02:26