Thursday, January 11, 2007

To copy a file in ...

... Java
private static void copyFile(File srcFile, File destFile) 
throws IOException {
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream(srcFile);
FileChannel iChannel = is.getChannel();
os = new FileOutputStream( destFile, false );
FileChannel oChannel = os.getChannel();
oChannel.transferFrom( iChannel, 0, srcFile.length() );
}
finally {
if (is != null) is.close();
if (os != null) os.close();
}
}

... Groovy
static void copyFile(File source, File destination) {
def reader = source.newReader()
destination.withWriter { writer ->
writer << reader
}
reader.close()
}

... Groovy with a salt of Ant
static void copyFile(File source, File destination) {
new AntBuilder().copy(file:'$source.canonicalPath',
tofile:'$destination.canonicalPath')
}

... in shell
cp source destination

10 comments:

Anonymous said...

Well you can still use in java the commons IO: FileUtils.copyFile(file,file);
It just takes one line ;-)

Unknown said...

Well, but this is unfair, because it's about of the box code.
The funny thing is that I looked for such a thing in jakarta commons and did not find it :-)

Allen Parslow said...

One of the interesting side effects of the apache commons library is that it makes it a little harder to find things (i.e. java severely suffers from code fragmentation).
I'm not sure why apache never gives back their libraries into the JDK.
I'm also not sure why JSR lifecycles are so long (what is being done to JSR each working hour of the lifecycle)?

Anonymous said...

What's about

def src = new FileInputStream(source)
def dst = new FileOutputStream(destination)
dst << src

Anonymous said...

Using AntBuilder (packaged with groovy) ...

ant.copy(file : fromFileName, tofile : toFileName, overwrite : true)

Shred said...

The groovy example damages the copied file on machines with UTF-8 charset! Better use Streams instead of Writers.

Unknown said...

new File(targetPath).bytes = new File(sourcePath).bytes

Work only in groovyConsole, but don't work with Groovy Eclipse project, why?

Lukas Rossa said...

Also the groovy AntBuilder example requires other dependencies such as ant jar etc.

gway dust said...

for text file, overwrite:
new File(fileA).text = new File(fileB).text

gway dust said...

for text, overwrite:

new File(fileA).text = new File(fileB).text