使用Java重命名文件

218

我们能否将一个名为test.txt的文件重命名为test1.txt

如果test1.txt已存在,它会被重命名吗?

如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?


10
您最后一段并没有描述重命名操作,而是描述了添加操作。 - user207421
15个回答

2
据我所知,重命名文件不会将其内容附加到目标名称的现有文件中。
关于在Java中重命名文件,请查看File类中renameTo()方法的文档

1

这是我成功重命名文件夹中多个文件的代码:

public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
    if(newName == null || newName.equals("")) {
        System.out.println("New name cannot be null or empty");
        return;
    }
    if(extension == null || extension.equals("")) {
        System.out.println("Extension cannot be null or empty");
        return;
    }

    File dir = new File(folderPath);

    int i = 1;
    if (dir.isDirectory()) { // make sure it's a directory
        for (final File f : dir.listFiles()) {
            try {
                File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);

                if(f.renameTo(newfile)){
                    System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
                } else {
                    System.out.println("Rename failed");
                }
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

并运行它作为一个示例:

renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");

1
Files.move(file.toPath(), fileNew.toPath()); 

这个方法可以起作用,但只有在关闭(或自动关闭)所有使用的资源(InputStreamFileOutputStream等)后才能实现。我认为 file.renameToFileUtils.moveFile 也是同样的情况。


0
我不喜欢使用java.io.File.renameTo(...),因为有时它无法重命名文件,而且你不知道原因!它只返回true或false。如果它失败了,它不会抛出异常。
另一方面,java.nio.file.Files.move(...)更有用,因为它在失败时会抛出异常。

-2

代码已经在此处运行。

private static void renameFile(File fileName) {

    FileOutputStream fileOutputStream =null;

    BufferedReader br = null;
    FileReader fr = null;

    String newFileName = "yourNewFileName"

    try {
        fileOutputStream = new FileOutputStream(newFileName);

        fr = new FileReader(fileName);
        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            fileOutputStream.write(("\n"+sCurrentLine).getBytes());
        }

        fileOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
            if (br != null)
                br.close();

            if (fr != null)
                fr.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

3
通常来说,解释一个解决方案比仅仅发布一些匿名代码更好。您可以阅读《如何写出一个好答案》和《解释完全基于代码的答案》,以获取更多信息。 - Anh Pham
1
复制和重命名通常是不同的操作,因此我认为应该明确标记这是一个复制。这也会导致不必要的缓慢,因为它复制字符而不是字节。 - Joel Klinghed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接