java getname file_Java File getName()用法及代码示例

getName()方法是File类的一部分。此函数返回给定文件对象的名称。该函数返回一个包含给定文件对象名称的字符串对象。如果抽象路径不包含任何名称,则返回一个空字符串。

函数签名:

public String getName()

函数语法:

file.getName()

参数:该函数不接受任何参数。

返回值:此函数返回一个字符串值,该值是给定File对象的名称。

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

范例1:我们得到了文件的文件对象,我们必须获取文件对象的名称。

// Java program to demonstrate the

// use of getName() function

import java.io.*;

public class solution {

public static void main(String args[])

{

// try-catch block to handle exceptions

try {

// Create a file object

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

// Get the Name of the given file f

String Name = f.getName();

// Display the file Name of the file object

System.out.println("File Name : " + Name);

}

catch (Exception e) {

System.err.println(e.getMessage());

}

}

}

输出:

File Name : program.txt

a4f79acdfa02340ae0c6d8289f75fd82.png

范例2:我们得到了目录的文件对象,我们必须获取文件对象的名称。

// Java program to demonstrate the

// use of getName() function

import java.io.*;

public class solution {

public static void main(String args[])

{

// try-catch block to handle exceptions

try {

// Create a file object

File f

= new File("c:\\users\\program");

// Get the Name of the given file f

String Name = f.getName();

// Display the file Name

// of the file object

System.out.println("File Name : "

+ Name);

}

catch (Exception e) {

System.err.println(e.getMessage());

}

}

}

输出:

File Name :program

47a73d7b8b41902efe4d0bf14d43cfd1.png

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值