Q:

Writing bytes into a file by blocks in java

I am currently writing an application which has a result a file this is composed by blocks of bytes that are processed in blocks so the goal is to process one block convert it into bytes and write(append) that block of bytes into the file then process the next block and so on..until it finishes having all of the bytes of all of the blocks stored into the file, i have been trying using the following piece of code: 
try (ObjectOutputStream oos = new ObjectOutputStream(file)) {
    oos.writeObject(bytestobwritten);
    oos.flush();
    oos.close();
    stat = 1;
} catch(FileNotFoundException ex) {
    Logger.getLogger(Filer.class.getName()).log(Level.WARNING, "Error by writing block of bytes", ex);                 
} //end catch 

The above code is inside the while structure that process the bytes the variable bytestobwritten contains the bytes of the current block
The issue here is that it is not appending all of the bytes only remains the last block of bytes..i need all of them being "Concatenated" to make the result amount of bytes for that file..
do you have any idea on how to deal with this situation in java? will appreciate any help, thanks in advance.

A:

So I'm not sure you understand your problem you're trying to solve.  But first ditch ObjectOutputStream for now.  We can use OutputStream (or DataOutputStream) to write bytes.
When you talk about writing blocks of bytes to a file you have to answer the question: Are all blocks the same size?  That's really important because if you write blocks with varying lengths you won't be able to read it back in because you don't know where a block begins and ends.  You will need to know the size of the next block before you read it.  If it's fixed block size that changes the code, but fixed block sizes has the limitation that no one block can be bigger than the block size.
public saveBLocks( List<Block> blocks ) {
    DataOutputStream stream = new DataOutputStream( new FileOutputStream( "someFile.txt" ) );
    try {
        for( int i = 0; i < blocks.size(); i++ ) {
           byte[] buffer = createBuffer( blocks.get(i) );

           // save out the block size to the stream if we have varying block size
           stream.writeInt( buffer.length );

           // save the block, assumes buffer is the exact size of the block
           stream.write( buffer, 0, buffer.length );
        }
        stream.flush();
    } finally {
        stream.close();
    }
}

After reading part of your question I wonder if you are just copying bytes between two streams which makes this simpler, and you don't really have to worry about blocks per se.

