Monday, September 24, 2012

Copy File from one directory to other directory




Let us suppose  I have a file  "hi.txt"  in One directory  and I want to copy the fille to other location with the name "bye.txt".
Using java , We can  achieve this functionality by making use of transferring in bytes ....

Following program illustrates how it can be done.



import java.io.*;
public class Main
{
public static void main(String a[])
    {
    try
        {
       // The source location is pointed by  inputstream object "in"
        InputStream in = new FileInputStream("D:\\hi.txt");

       // The destination location is pointed by  outputstream object "obj"
        OutputStream out = new FileOutputStream("E:\\bye.txt");

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
    catch (Exception exception)
    {
        System.out.println("Exception "+exception.printStackTrace());
    }
    }
}

No comments:

Post a Comment