首页 > 解决方案 > 如何在Windows的同一目录中复制给定不同名称的文件

问题描述

我一直在尝试复制一个文件,但在同一个 Windows 目录中更改它的名称,但我没有运气。

我不能只复制同一目录中的文件,因为 Windows 规则两个文件不能在同一目录中具有相同的名称。

我不允许将其复制到另一个目录然后重命名它,然后将其移回同一目录中。

而且我在File.class.

尝试过类似的方法,但没有奏效:

File file = new File(filePath);
File copiedFile = new File(filePath);
//then rename the copiedFile and then try to copy it
Files.copy(file, copiedFile);

标签: javajava-8

解决方案


您可以在同一目录中创建一个新文件,然后将原始文件的内容复制到副本请参阅:Java read from one file and write into another file using methods 了解更多信息

您还可以使用https://www.journaldev.com/861/java-copy-file中的此代码段

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

推荐阅读