Store 2D array (String) to file and retrieve it

后端 未结 3 691
广开言路
广开言路 2021-01-15 21:30

I have made a simple program that has a 2D String array storing lots of data. I have searched a lot of places for how to store and retrieve 2D arrays. I want to save the dat

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 21:58

    There is an additional question to resolve, which is how do you store the sizes of the arrays as well as the contents. I would recommend using conversion to JSON. If you get the Jackson library, you should be able to use the Jackson Object Mapper. I would recommend storing your arrays within another object.

    e.g.

    class MyClass {
        String[][] myArray;
    
        // add the getters and setters to this class for myArray too
    }
    

    Then for storing

    MyClass myObject = new MyClass();
    
    // set the arrays here to whatever you like
    
    ObjectMapper mapper = new ObjectMapper();
    mapper.write(new File("c:\somedir\somefile.txt"), myObject);
    

    Then for loading

    ObjectMapper mapper = new ObjectMapper();
    MyClass loaded = mapper.readValue(new File("c:\somedir\somefile.txt", MyClass.class);
    
    // then you can use loaded as the source of your data
    

提交回复
热议问题