java renameto 实时_Java File renameTo()用法及代码示例

renameTo()方法是File类的一部分。 renameTo()函数用于将文件的抽象路径名重命名为给定的路径名​​。如果文件被重命名,该函数返回true,否则返回false

函数签名:

public boolean renameTo(File destination)

用法:

file.renameTo(File destination)

参数:该函数需要File对象的目标位置作为参数,即当前文件的新抽象路径名。

返回值:该函数返回布尔数据类型。该函数返回true文件已重命名,否则返回false

异常:此方法引发以下异常:

安全异常如果该方法不允许抽象路径名的写操作。

NullPointerException如果目标文件名为null。

下面的程序将说明renameTo()函数的用法:

范例1:尝试将文件program.txt重命名为program1.txt

// Java program to demonstrate

// the use of File.renameTo() method

import java.io.*;

public class GFG {

public static void main(String args[])

{

// create an abstract pathname (File object)

File f = new File("F:\\program.txt");

// create the destination file object

File dest = new File("F:\\program1.txt");

// check if the file can be renamed

// to the abstract path name

if (f.renameTo(dest)) {

// display that the file is renamed

// to the abstract path name

System.out.println("File is renamed");

}

else {

// display that the file cannot be renamed

// to the abstract path name

System.out.println("File cannot be renamed");

}

}

}

输出:

File is renamed

范例2:尝试将“program1.txt”重命名为“prog.txt”,“prog.txt”是f:驱动器中的现有文件。

// Java program to demonstrate

// the use of File.renameTo() method

import java.io.*;

public class GFG {

public static void main(String args[])

{

// create an abstract pathname (File object)

File f = new File("F:\\program1.txt");

// create the destination file object

File dest = new File("F:\\prog.txt");

// check if the file can be renamed

// to the abstract path name

if (f.renameTo(dest)) {

// display that the file is renamed

// to the abstract path name

System.out.println("File is renamed");

}

else {

// display that the file cannot be renamed

// to the abstract path name

System.out.println("File cannot be renamed");

}

}

}

输出:

File cannot be renamed

这些程序可能无法在在线IDE中运行。请使用离线IDE并设置文件的路径

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值