我在 WINDOWS
上使用这个脚本public void copyFile(File sourceDirectory, File targetFile, File targetDirectory) throws IOException{
String temp = targetFile.getAbsolutePath();
String relativeD = temp.substring(sourceDirectory.getAbsolutePath().length(), targetFile.getAbsolutePath().length());
String rootD = sourceDirectory.getName();
String fullPath = targetDirectory.getAbsolutePath() + rootD + relativeD;
File fP = new File( fullPath );
System.out.println("PATH: " + fullPath);
FileChannel inChannel = new FileInputStream(targetFile).getChannel();
FileChannel outChannel = new FileOutputStream( fP ).getChannel();
int maxCount = (64 * 1024 * 1024) - (32 * 1024);
long size = inChannel.size();
long position = 0;
while (position < size) {
position += inChannel.transferTo(position, maxCount, outChannel);
}
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
我所做的很简单。我需要将文件从一个位置复制到另一个位置,但我必须保留它们所在的目录。
所以对于 relativeD
,我采用这样的方式:dir/files.sql 或简单的 files.sql。
发生这种情况是因为对于特定目录,我需要按照树结构递归地复制它们。
问题是这个方法不起作用。我不知道为什么,因为如果我使用一个简单的
FileChannel outChannel = new FileOutputStream( new File( targetDirectory, targetFile ) ).getChannel();
它有效。我想这是因为在这种情况下它正在将文件复制到现有目录下。
最佳答案
根据这个article (“java mkdir recursive”在谷歌搜索中排名最高):
Have a look at the java.io.File : it does the job perfectly, with the mkdirs function :
new File("c:/aaa/bbb/ccc/ddd").mkdirs();
关于java - 将文件写入仍然不存在的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4485584/