tags:

views:

908

answers:

5

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.

+4  A: 

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.

OscarRyz
+6  A: 

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
Greg Case
A: 

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.

sblundy
+1  A: 

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. :)

Bill the Lizard
for(int i=0;i<5000000000;i++) file.write(" "); (Yeah, I know it would probably take a while, but the comment about not having the 5gb file around was amusing in context)
Bill K
this should get you a 5gb file pretty quick: dd if=/dev/zero of=foobar count=5242880 bs=1024
rmeador
or for NTFS: fsutil file createnew 5gb.bin 5000000000
Guge
+2  A: 

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 :)

Filip Ekberg
I think you mean 2^32
Mike
Yeah, 32^2 is only 1024. 2^32 is 4294967296.
sep332
Well. I have a 32 bit OS (Win XP) and I can open the file and seek to any position in files larger than 5 GB using C#. FileStream.Seek takes a long integer, 2^64.
Guge
No, that really doesn't have anything to do with the 32 bit memory limit.
Henning
Sorry ofc i mean 2^32. And that isn't really a memory limit my friend but a limit for the CPU. It's possible though to simulate more than 32Bit. As it was many years ago, when float didnt exist :)
Filip Ekberg