即使我以管理员身份运行,也无法复制文件(访问被拒绝)

时间:2020-07-23 02:46:55

标签: java io

我正在尝试制作一个将文件从一个驱动器复制到另一个驱动器的应用程序,但是由于某种原因,它始终会给我一个错误,即使我以管理员身份运行并且该帐户是运行该应用程序是设备上的唯一帐户。我知道我有权前往目的地,因为

  1. 大量文件(n个文件中)能够成功复制到目标位置
  2. 我已授予用户对该目录的完全权限
  3. 目标是外部存储驱动器。
  4. 我可以在该目的地的目录中创建一个新文件

另外:我在Windows 10上

复制功能:

private void c2cTransfer(Path source, Path dest) throws Exception {
    // Get channel for output file
    FileOutputStream fos = new FileOutputStream(dest.toFile());
    WritableByteChannel targetChannel = fos.getChannel();

    // Get channel for input files
    FileInputStream fis = new FileInputStream(source.toString());
    FileChannel inputChannel = fis.getChannel();

    System.out.print("Closing all IO readers...\t");
    // Transfer data from input channel to output channel
    inputChannel.transferTo(0, inputChannel.size(), targetChannel);

    // close the input channel
    inputChannel.close();
    fis.close();

    // finally close the target channel
    targetChannel.close();
    fos.close();
}

调用函数的地方:

        if (newPath.toFile().canWrite()) {
            c2cTransfer(f, newPath); // Start transfer
            System.out.printf("Complete!\n");
        } else {
            // Keep jumping to here.
            System.err.printf("Failed!\nYou do not have permission to write to: %s\n", newLocation);
            failedTransfer.add(f);
        }

1 个答案:

答案 0 :(得分:0)

找出需要事先存在的文件,所以我的解决方法是:

if (!newPath.toFile().exists()) {
    newPath.toFile().getParentFile().mkdirs();
    newPath.toFile().createNewFile();
}

尽管我有一个或两个文件,即使该文件存在,并且仍具有我的完全许可权,但该文件仍使我无法访问。因此,我刚刚做了一个覆盖功能,该功能仅删除旧文件并写入新副本。