将文件夹及其文件复制到另一个位置

时间:2009-12-25 12:55:38

标签: java

我想将F:\ test复制到文件夹F:\ 123,以便我有文件夹F:\ 123 \ test。

在测试文件夹中我有两个文件:input和output.java 但我不能这样做错误是: F \ 123 \ test \ output.java(系统找不到指定的路径)

这是我的代码:

    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());
    }

这是copyFolder函数

 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();
}

请帮我解决我的错误。

2 个答案:

答案 0 :(得分:3)

Constant.toPath = "F\\123\\test";应为Constant.toPath = "F:\\123\\test";

答案 1 :(得分:2)

您可能需要查看Apache Commons FileUtils,特别是各种copyDirectory()方法。如上所述,它将为您节省大量繁琐的编码。