Search code examples
javafilestreamdataoutputstream

Read and write from a file in different classes without having to close the stream in java


hey everyone :] just wondering if is it possible to read and write from a file in different classes without having to close the stream and start over again?

i need to use DataOutputStream and DataInputStream. i currently have 2 classes, my first class are supposed to write all objects to a file. Depending of what kind of object it is. I will be sending the object to a different class where it will continue writing.

the problem is that either i will just make to write 1 object before the stream is closed and i can't continue writing the next object, or each object will overwrite the last object.

    public int skrivTilFil( String filnavn)
  {
      try{DataOutputStream input = new DataOutputStream(new FileOutputStream(filnavn)))
      {
          Bok løper = første;
          {
              while(løper != null)
              {
                  if(løper instanceof Skolebok)
                  {
                      Skolebok bok = (Skolebok) løper;
                      bok.skrivObjektTilFil(input);
                  }

                  løper = løper.neste;
              }
          }
      }
  }




public void skrivObjektTilFil(DataOutputStream output) // skolebok class
         {
             try
             { 
                            output.writeUTF("Skolefag");
                output.writeInt(klassetrinn);
                output.writeUTF(skolefag);
                super.skrivObjektTilFil(output);
             }catch(IOException e)
             {               
                            System.out.println("General I/O exception: "
                            e.getMessage());e.printStackTrace(); 
                        }
         }

here i will get IOException because the stream is closed, so i can't continue with the next object, but if i set DataOutputStream in the second class, i will be overwritting each object. is there i simple solution to this problem?


Solution

  • You need to append to the FileOutputStream.

    You should modify its creation as in:

    ...                                                                           
    try{DataOutputStream input =                                  //append
                new DataOutputStream(new FileOutputStream(filnavn,true)))
    ...