This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes I/O and Streams and the fly likes Maintaining File Size while writing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Maintaining File Size while writing" Watch "Maintaining File Size while writing" New topic
Author

Maintaining File Size while writing

Amirr Rafique
Ranch Hand

Joined: Nov 14, 2005
Posts: 324
Hello

I am writing my data contained in POJO to a file. I want to make sure the file does not exceeds to a fixed size e.g. 1MB. Say I have list of 50 Objects of Person type each objects size may vary due to string attributes length. While writing these objects I want to make sure my file size does not exceeds from 1MB. How can I calculate size of object before writing it to stream or how can I undo last written object on stream

Please help


"Know where to find the solution and how to use it - that's the secret of success."
Amirr Rafique
Ranch Hand

Joined: Nov 14, 2005
Posts: 324

Any idea!!!

Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2956
    
  12

We generally counsel patience (PatienceIsAVirtue) here at the Ranch. However, I can understand how you'd get antsy after three days with no replies.

One solution is to stream your objects into memory using a ByteArrayOutputStream. That will let you get your serialized object as a byte array, so you can see how big it is. Then you can stream the byte array out to your file. Another solution would be to record the current size of your file, stream the object to it, then truncate the file back to the original size if it got too big.
Amirr Rafique
Ranch Hand

Joined: Nov 14, 2005
Posts: 324
Thanks Grep
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Maintaining File Size while writing
 
It's not a secret anymore!