windows 将文件写入仍然不存在的目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4485584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:49:35  来源:igfitidea点击:

Writing files into a directory which still does not exists

javawindowsfile-io

提问by dierre

I'm using this script on WINDOWS

我在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();
}

What I'm doing is simple. I need to copy a file from a location to another but I have to keep the directories they're in.

我正在做的很简单。我需要将文件从一个位置复制到另一个位置,但我必须保留它们所在的目录。

So with relativeDI'm taking something like this: dir/files.sqlor simply files.sql.

因此,relativeD我采用了这样的方法:dir/files.sql或简单的files.sql

This is happening because for specific directories I need to copy them recursively respecting the tree structure.

发生这种情况是因为对于特定目录,我需要按照树结构递归复制它们。

The problem is this method is not working. I don't know why because if I use a simple

问题是这种方法不起作用。我不知道为什么,因为如果我使用一个简单的

    FileChannel outChannel = new FileOutputStream( new File( targetDirectory, targetFile ) ).getChannel();

it works. I suppose this is happening because in this case it's copying the file under an existing directory.

有用。我想这是因为在这种情况下它正在将文件复制到现有目录下。

回答by Jonathan Leffler

According to this article(top Google search hit for 'java mkdir recursive'):

根据这篇文章(“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.io.File :它使用 mkdirs 函数完美地完成了这项工作:

    new File("c:/aaa/bbb/ccc/ddd").mkdirs();