[英]I'm trying to Rename a File using Java But It is Not Working for Some Reason
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");
}
我正計划將其開發為文件規范化器,但我只想先完成它。 我嘗試使用絕對路徑,沒有區別。 不斷返回“重命名失敗”。
使用Files類的move方法。 為我工作;)
如果您使用的是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();
}
使用FileChooser(); File 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");
}
}
這是我的新代碼,它可以使用文件選擇器工作,但目前僅當我從桌面選擇文件時才有效,因此使用硬編碼子字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.