我正在尝试使用以下代码将文件复制到可能不存在的路径:
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丢失,因此程序应该创建它们。