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

6 comments to To copy a file in …

  • pierre-yves

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

  • Emmanuel Bernard

    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

    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

    What's about

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

  • Anonymous

    Using AntBuilder (packaged with groovy) …

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

  • Shred

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

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>