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

标签 java

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

在测试文件夹中我有 2 个文件: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());
    }

复制文件夹函数

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

请帮助我修复我的错误。

最佳答案

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

关于java - 将文件夹及其文件复制到另一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1961129/

相关文章:

java - 我无法使用actionPerformed()方法处理JButton点击事件,不要进入该方法,为什么?

java - hibernate 组织. hibernate .LazyInitializationException : failed to lazily initialize a collection of role:

java - 如何在 ClickListener 上设置绘图线?

java - 为什么我的应用程序在尝试建立 http 连接时不断崩溃?

java - 我如何检查 ImageView 是否为空

Java 在 Linux 上使用 100% 的 CPU

java - 为什么java编译器不检查未经检查的异常?

Java进程构建器获取构建命令

java - com.mysql.jdbc.PacketTooBigException : Packet for query is too large (8548 > 1024)

java - 采取动态输入的一副纸牌