0

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?

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
Madde
  • 471
  • 1
  • 7
  • 22
  • I dont know which language you have written this code in, so i have not understood it completely.. is your objective to pass the DataOutputStream from first to second class without closing it/overwriting the target file? – aksappy Feb 15 '13 at 15:56

2 Answers2

2

You need to append to the FileOutputStream.

You should modify its creation as in:

...                                                                           
try{DataOutputStream input =                                  //append
            new DataOutputStream(new FileOutputStream(filnavn,true)))
...
Carlo Pellegrini
  • 5,656
  • 40
  • 45
0

You can pass the DataOutputStream from one class/method to another as you would pass any other object. You can keep writing to it from any class/method that you passed it, as long as it hasn't been closed. As a best practice, the class responsible for opening the DataOutputStream should be responsible for closing it.

Andres Olarte
  • 4,380
  • 3
  • 24
  • 45