Chan Pye
Chan Pye

Reputation: 1391

Copy folder and its files to another location

I want to copy F:\test to folder F:\123 so that I have folder F:\123\test.

In test folder I hava 2 files: input and output.java But I can not do that erro is: F\123\test\output.java (The system cannot find the path specified)

Here is my code:

    Constant.fromPath = "F:\\test"
    Constant.toPath = "F\\123\\test";
    File source = new File(Constant.fromPath);
    File destination = new File(Constant.toPath);

    try
    {
        copyFolder(source, destination);

    }
    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }

Here is copyFolder function

 public static void copyFolder(File srcFolder, File destFolder) throws IOException
{
    if (srcFolder.isDirectory())
    {
        if (! destFolder.exists())
        {
            destFolder.mkdir();
        }

        String[] oChildren = srcFolder.list();
        for (int i=0; i < oChildren.length; i++)
        {
            copyFolder(new File(srcFolder, oChildren[i]), new File(destFolder, oChildren[i]));
        }
    }
    else
    {
        if(destFolder.isDirectory())
        {
            copyFile(srcFolder, new File(destFolder, srcFolder.getName()));
        }
        else
        {
            copyFile(srcFolder, destFolder);
        }
    }
}

public static void copyFile(File srcFile, File destFile) throws IOException
{
        InputStream oInStream = new FileInputStream(srcFile);
        OutputStream oOutStream = new FileOutputStream(destFile);

        // Transfer bytes from in to out
        byte[] oBytes = new byte[1024];
        int nLength;
        BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
        while ((nLength = oBuffInputStream.read(oBytes)) > 0)
        {
            oOutStream.write(oBytes, 0, nLength);
        }
        oInStream.close();
        oOutStream.close();
}

Pls help me to fix my bug.

Upvotes: 3

Views: 1753

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272417

You may want to check out Apache Commons FileUtils, and specifically the various copyDirectory() methods. It'll save you a lot of tiresome coding like the above.

Upvotes: 2

Gregory Pakosz
Gregory Pakosz

Reputation: 70254

Constant.toPath = "F\\123\\test"; should be Constant.toPath = "F:\\123\\test";

Upvotes: 3

Related Questions