javafile-ioiostreaminputstreamoutputstream

What is the proper way to write/read a file with different IO streams


I have a file that contains bytes, chars, and an object, all of which need to be written then read. What would be the best way to utilize Java's different IO streams for writing and reading these data types?

More specifically, is there a proper way to add delimiters and recognize those delimiters, then triggering what stream should be used? I believe I need some clarification on using multiple streams in the same file, something I have never studied before. A thorough explanation would be a sufficient answer.


Solution

  • As EJP already suggested, use ObjectOutputStream and ObjectInputStream an0d wrap your other elements as an object(s). I'm giving as an answer so I could show an example (it's hard to do it in comment) EJP - if you want to embed it in your question, please do and I'll delete the answer.

    class MyWrapedData implements serializeable{
        private String string1;
        private String string2;
        private char   char1;
        // constructors
        // getters setters
    }
    

    Write to file:

    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
    out.writeObject(myWrappedDataInstance);
    out.flush();
    

    Read from file

    ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
    Object obj = in.readObject();
    MyWrapedData wraped = null;
    if ((obj != null) && (obj instanceof MyWrappedData))
        wraped = (MyWrapedData)obj;
    // get the specific elements from the wraped object
    

    see very clear example here: Read and Write