Java gravel of the day: We're in outer space: copying files

jdavidb on 2008-03-05T21:32:43

Sure you can copy files in Java! It's easy! All you have to do is write a routine to read the contents of one file and write it to another file!

What do you mean, there should be a library routine to do this? What do you mean, you want to portably take advantage of whatever OS facilities exist to do this?

Is there something about "copying files in Java is easy" that doesn't make sense to you?


How Often Do You Need This?

Ovid on 2008-03-06T10:05:56

My question for Java developers is always the same: can you, without looking at the docs, write the code to open a file, read the first line from the file (delimited by a newline) and print said line? The answer is invariably "no, but ...".

The counter-argument is that since they don't need to do this very often, there's no need to optimize this. When you're working in an "enterprise" environment, you're not constantly opening and reading files. Just to prove this point, I ran this on our codebase here:

ack '^(?!\s*#)\s*\bopen\b' lib/ -l | wc -l

Hmm, that shows six modules. Further investigation shows that we open files seven times (actually, a bit more as that's a naïve regex). So maybe opening and reading files is common?

Or maybe, as I suspect, since it's so easy in Perl, we reach for it more.

Re:How Often Do You Need This?

lachoy on 2008-03-10T03:51:24

If you do need it, you stick it in a library. Something like:

String line = FileUtil.slurpLines( path | file )[0];
Or if you want it from the classpath, not just a file path:

String line = new Resource( classpath-ref ).slurpLines()[0];
File handling is one of my Java interview questions :-)