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:
Well you can still use in java the commons IO: FileUtils.copyFile(file,file);
It just takes one line ;-)
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 :-)
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)?
What's about
def src = new FileInputStream(source)
def dst = new FileOutputStream(destination)
dst << src
Using AntBuilder (packaged with groovy) ...
ant.copy(file : fromFileName, tofile : toFileName, overwrite : true)
The groovy example damages the copied file on machines with UTF-8 charset! Better use Streams instead of Writers.
new File(targetPath).bytes = new File(sourcePath).bytes
Work only in groovyConsole, but don't work with Groovy Eclipse project, why?
Also the groovy AntBuilder example requires other dependencies such as ant jar etc.
for text file, overwrite:
new File(fileA).text = new File(fileB).text
for text, overwrite:
new File(fileA).text = new File(fileB).text
Post a Comment