将java中的文件复制到可能不存在的目录

将java中的文件复制到可能不存在的目录,java,copy,Java,Copy,我正在尝试将文件复制到可能不存在此代码的路径 public static void copyFile( File from, File to ) throws IOException { if ( !to.exists() ) { to.createNewFile(); } try ( FileChannel in = new FileInputStream( from ).getChannel(); FileChannel out =

我正在尝试将文件复制到可能不存在此代码的路径

    public static void copyFile( File from, File to ) throws IOException {

    if ( !to.exists() ) { to.createNewFile(); }

    try (
        FileChannel in = new FileInputStream( from ).getChannel();
        FileChannel out = new FileOutputStream( to ).getChannel() ) {

        out.transferFrom( in, 0, in.size() );
    }
这显然是错误的,因为如果目录不存在,它就不会复制文件。它需要创建路径中不存在的文件夹

例如,程序应将文件复制到:

C:\test\test1\test2\test3\copiedFile.exe


其中C:\中的目录test存在,但缺少test2和test3,因此程序应该创建它们。

您可以使用下面的代码段创建所有路径,例如:

File file = new File("C:\\test\\test1\\test2\\test3\\copiedFile.exe");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
所以你必须到目录上去。