我正在尝试将文件复制到此代码可能不存在的路径
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);
关于java - 将java中的文件复制到可能不存在的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28614238/