No Relation To...


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

Labels:

6 Comments:

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

    By Anonymous pierre-yves, At January 16, 2007 8:20 AM  

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

    By Blogger Emmanuel Bernard, At January 16, 2007 1:16 PM  

  • 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)?

    By Blogger Allen Parslow, At April 14, 2008 9:50 AM  

  • What's about

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

    By Anonymous Anonymous, At September 9, 2008 11:49 AM  

  • Using AntBuilder (packaged with groovy) ...

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

    By Anonymous Anonymous, At February 19, 2009 7:19 PM  

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

    By Anonymous Shred, At December 30, 2009 8:20 AM  

Post a Comment



Links to this post:

Create a Link

<< Home