How to copy file in java

 Posted On  | Yashwant Chavan 

Java provides standard way of reading and writing the files. The Java package java.io contains classes which is used to read and write to files.

File Copy Program Using Java

Create a new Java Class "FileCopyExample.java" in Eclipse. The following example illustrates how to copy contents from one file to another file using java io classes.The File class is an abstract representation of file and directory path-names. FileReader is meant for reading streams of characters. and after reading the file it going to write into another file using FileWriter. This process continue till end of file occurred. Once the operation done we are closing or releasing the resources. in.close() and out.close();

package com.technicalkeeda.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileCopyExample {
    public static void main(String[] args) {
        new FileCopyExample().fileCopy("fileA.txt", "fileB.txt");
    }

    public void fileCopy(String sourceFile, String desinationFile) {
        try {
            File inputFile = new File(sourceFile);
            File outputFile = new File(desinationFile);

            FileReader in = new FileReader(inputFile);
            FileWriter out = new FileWriter(outputFile);
            int c;

            while ((c = in .read()) != -1)
                out.write(c);

            in .close();
            out.close();
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IOException" + e.getMessage());
        }
    }
}


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0336 seconds.