我尝试使用Java重命名文件,但由于某些原因它不起作用

时间:2014-11-27 13:48:59

标签: java file boolean filepath file-rename

File oldfile = new File("C:\\NewText Document.txt");
File newfile = new File("C:\\Hello Buddy.txt");

if (oldfile.renameTo(newfile))
{
   System.out.println("Rename succesful");
}
else
{
   System.out.println("Rename failed");
}

我打算将它开发成文件规范化程序,但我只想先完成这项工作。 我尝试过使用绝对路径,没有任何区别。不断返回“重命名失败”。

3 个答案:

答案 0 :(得分:1)

使用Files类的move方法。为我工作;)

Java doc

答案 1 :(得分:1)

如果您使用的是Java 7,请尝试以下操作:

    final File oldfile = new File("C:\\NewText Document.txt");
    final File newfile = new File("C:\\Hello Buddy.txt");

    final Path source = oldfile.toPath();
    final Path dest=newfile.toPath();

    try {
         Files.move(source, dest);
    } catch (IOException e) {
         e.printStackTrace();
    }

答案 2 :(得分:0)

使用FileChooser();         文件oldfile = new File(fileName);

    File newfile = new File(fileName.substring(0, 21) + "hello world.txt");
    if (!oldfile.exists())
    {
        try
        {
            oldfile.createNewFile();
        }
        catch (IOException ex)
        {
            System.out.println(ex);
        }
    }
    else
    {

        if (oldfile.renameTo(newfile))
        {

            System.out.println("Rename succesful");
        }
        else
        {
            System.out.println("Rename failed");
        }
    }

这是我的新代码,它使用文件选择器,但目前它只有在我从我的桌面选择文件时才有效,因此硬编码的子字符串。