【问题标题】:I'm trying to Rename a File using Java But It is Not Working for Some Reason我正在尝试使用 Java 重命名文件,但由于某种原因它不起作用
【发布时间】:2014-11-27 13:48:59
【问题描述】:
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");
}

我正计划将它开发成一个文件规范器,但我只想先完成它。 我试过使用绝对路径,没有区别。不断返回“重命名失败”。

【问题讨论】:

标签: java file boolean filepath file-rename


【解决方案1】:

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

Java doc

【讨论】:

    【解决方案2】:

    如果您使用的是 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();
        }
    

    【讨论】:

      【解决方案3】:

      FileChooser(); 文件旧文件 = 新文件(文件名);

          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");
              }
          }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多