javafilebinarypersistent-storage

Write Java objects to file


Is it possible to write objects in Java to a binary file? The objects I want to write would be 2 arrays of String objects. The reason I want to do this is to save persistent data. If there is some easier way to do this let me know.


Solution

  • If you want to write arrays of String, you may be better off with a text file. The advantage of using a text file is that it can be easily viewed, edited and is usuable by many other tools in your system which mean you don't have to have to write these tools yourself.

    You can also find that a simple text format will be faster and more compact than using XML or JSON. Note: Those formats are more useful for complex data structures.

    public static void writeArray(PrintStream ps, String... strings) {
        for (String string : strings) {
            assert !string.contains("\n") && string.length()>0;
            ps.println(strings);
        }
        ps.println();
    }
    
    public static String[] readArray(BufferedReader br) throws IOException {
        List<String> strings = new ArrayList<String>();
        String string;
        while((string = br.readLine()) != null) {
            if (string.length() == 0)
                break;
            strings.add(string);
        }
        return strings.toArray(new String[strings.size()]);
    }
    

    If your start with

    String[][] theData = { { "a0 r0", "a0 r1", "a0 r2" } {"r1 c1"} }; 
    

    This could result in

    a0 r0
    a0 r1
    a0 r2
    
    r1 c1
    

    As you can see this is easy to edit/view.

    This makes some assumptions about what a string can contain (see the asset). If these assumptions are not valid, there are way of working around this.