我正在尝试将文件复制到此代码可能不存在的路径
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() );
}
Run Code Online (Sandbox Code Playgroud)
这显然是错误的,因为如果目录不存在,则不会复制文件。它需要创建路径中不存在的文件夹。
例如,程序应将文件复制到:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2753 次 |
| 最近记录: |