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

标签 java windows file-io

我在 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/

相关文章:

windows - 使用 WinSCP get 命令下载两种类型的文件(*.bat 和 *.txt)

python - 在 python 中将 namedtuple 写入和读取文件

java - 在Android中,我写入文件时的默认目录在哪里?

java - 使用 swing 启动 Jade 代理

java - 使用 java System.getProperty ("Import")

php - 在 Windows 上使用 PHP 获取总可用系统内存

大块/内存管理中的python read()和write()

java - Java 和 PHP 应用程序中的全文搜索支持

java - 动态调整 JScrollPane 的大小?

eclipse - 使用适用于 Linux 的 Windows 子系统在 eclipse 上设置 Linux gcc 工具链/编译器