Copying a file with Java using FileUtils

Description:

The piece of code below shows you how to copy or duplicate a file using Java. To do this task, we are going to use an important library from java. 

Important tips for Eclipse users:
  • Make sure to add the file you desire to duplicate in your project. The file should be added in the directory that contains src folder and NOT in the src folder where your .java files are located.
  • Make sure to download the "commons-io-2.4.jar" library. It is available on our Downloads page. 
  • Make sure also to add this library to your project. If you don't know how, click here.
  • After you execute your code, refresh the directory and you'll see your copied file.


Solution:

package com.javaproblems.files;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class CopyingFiles {

 
 public static void main(String[] args) {
  try {
   File f1 = new File("SrcFile.txt");
   File f2 = new File("TrgtFile.txt");
   
   FileUtils.copyFile(f1, f2);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact