Can I write to the end of a 5GB file in Java? This question came up in my office and no one is sure what the answer is.
Yes. Take a look at this link RandomAccessFile
http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html#seek(long)
That is , you open the file, and then set the position to the end of the file. And start writing from there.
Tell us how it went.
This should be possible fairly easily using a RandomAccessFile. Something like the following should work:
String filename;
RandomAccessFile myFile = new RandomAccessFile(filename, "rw");
// Set write pointer to the end of the file
myFile.seek(myFile.length());
// Write to end of file here
5GB? I wonder if the OS is a bigger problem, but that's doubtful.
In theory, you can just open the file in append mode.
OutputStream in = new java.io.FileOutputStream(fileName, true);
and write till the filesystem fills up.
See Bill the Lizard for char data.
If you just mean that you need to append to the file, check out the
FileWriter(File file, boolean append)
constructor in the FileWriter class.
Sorry, I don't have a 5GB file handy to test with. :)
Actually that would depend on the underlying File System and how the JVM on that platform implements the File Stream. Because, if a file is bigger than 5GB you cannot, with a 32Bit operative system open the whole file and just write to it, because of the 4.3 Billion limit stuff ( 32^2 ).
So, the answer shortly would be, Yes, it is possible, IF Java handles the file correctly and the File System is a good one :)