How to copy file content using Java


In this article we are going to discuss about how to copy file content to another file

Filename:sourceFile.txt
site1 = www.google.com
site2 = www.becbe.com
site3 = www.linux.com
site4 = www.motorola.com
site5 = www.apple.com
Filename: targetFile.txt
sample file

Filename: FileCopyTest .java

package com.becbe.java.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
 * This class shows demo to copy file content
 * @author bebce
 *
 */
public class FileCopyTest {

 public static String sourceFilePath="d:\\sourceFile.txt";
 public static String targetPath="d:\\targetFile.txt";
 /**
  * This method is used to copy content from one file other
  * @param sourceFile
  * @param targetFile
  * @return
  */
 public static boolean copy(File sourceFile, File targetFile)
 {
  boolean success = false;
  //File availability verification
     if(!sourceFile.exists() || !targetFile.exists())
     {
      return false;
     }
  try {
   //Reading file content from source File
   FileInputStream sourceFileStream = new FileInputStream(sourceFile);
   FileChannel sourceFileChannel = sourceFileStream.getChannel();
   //writing file content 
   FileOutputStream targetFileStream = new FileOutputStream(targetFile);
   FileChannel targetFileChannel=targetFileStream.getChannel();
   //copy file content
   sourceFileChannel.transferTo(0, sourceFile.length(), targetFileChannel);
   success = true;
  }
  catch (Exception e) {
   // TODO: handle exception
   
  }
    
  return success;
 }
 
 /**
  * @param args
  * @throws IOException 
  */
 public static void main(String[] args) {
  FileCopyTest cpTest=new FileCopyTest(); 
     File sourceFile = new File(cpTest.sourceFilePath);
     File targetFile = new File(cpTest.targetPath);
      if(cpTest.copy(sourceFile, targetFile))
     {
      System.out.println("File copied successfully ");
     }else{
      System.out.println("File copy operation failed ");
     }
     
  
 }

}


Output:
File copied successfully 
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment