Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Easy way to copy a file?  RSS feed

 
Matt Senecal
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to copy a file from one location on disk to another. All I know about the file is it's location and that it was written with an ObjectOutputStream.
I tried to copy it like this:

But that just moved the file from one location to the other. Is there another way of doing this?
 
Matt Senecal
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's how I solved it:
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Streams works fine, but you might get better performance using java.io.RandomAccessFile . Streams have quite a lot of infrastructure that you just do not need for a simple file copying operation.
If you can be sure that your files are not too big, you can read the whole source file into a byte array with one operation on a RandomAccessFile (opened "r") and write it to the target file with one operation on a second RandomAccessFile (opened "w"). If could be big, read/write it in chunks using a loop rather like the one you used for streams.
Opening the target RandomAccessFile will cause it to get created, too. No need for explicit creation (but do check, if necessary, that no such file already exists).
 
Matt Senecal
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the tip! I'll look into it.
 
Brett Delia
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:
...
If you can be sure that your files are not too big, you can read the whole source file into a byte array with one operation on a ...

What is meant by too big of a file?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By "if your file is not too big" I mean, can you spare enough heap to load the whole file into memory at once. This is only a good idea if you know the size of the file, with reasonable certainty.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!