Java examples on commons.io
- How do I read file contents to string using commons-io?
- How do I write string data to file?
- How do I search for files recursively?
- How do I read text file content line by line using commons-io?
- How do I create a copy of a file?
- How do I delete directory recursively?
- How do I touch a file?
- How do I sort files base on their last modified date?
- How do I calculate directory size?
- How do I create a human-readable file size?
- How do I read a file into byte array using Commons IO?
- How do I copy a URL into a file?
- How do I get the content of an InputStream as a String?
- How do I copy directory with all its contents to another directory?
- How do I move directory to another directory with its entire contents?
- How do I get free space of a drive or volume?
- How do I create File object from URL?
How do I create a copy of a file?
This example shows how we can use the apache commons-io library to simplify a file copy process.
package org.kodejava.example.commons.io;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class FileCopyExample
{
public static void main(String[] args)
{
// The source file name to be copied.
File source = new File("january.doc");
// The target file name to which the source file will be copied.
File target = new File("january-backup.doc");
// A temporary folder where we are gonna copy the source file to.
// Here we use the temporary folder of the OS, which can be obtained
// using java.io.tmpdir property.
File targetDir = new File(System.getProperty("java.io.tmpdir"));
try
{
// Using FileUtils.copyFile() method to copy a file.
System.out.println("Copying " + source + " file to " + target);
FileUtils.copyFile(source, target);
// To copy a file to a specified folder we can use the
// FileUtils.copyFileToDirectory() method.
System.out.println("Copying " + source + " file to " + targetDir);
FileUtils.copyFileToDirectory(source, targetDir);
} catch (IOException e)
{
// Errors will be reported here if any error occures during copying
// the file
e.printStackTrace();
}
}
}