Java File getName()方法及示例
getName() 方法是File类的一部分。这个函数返回给定文件对象的名称。该函数返回一个字符串对象,其中包含给定文件对象的名称。如果抽象路径不包含任何名称,则返回一个空字符串。
函数签名 。
public String getName()
函数语法
file.getName()
参数: 该函数不接受任何参数。
返回值: 该函数返回一个字符串值,即给定文件对象的名称。
下面的程序将说明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
例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
这些程序可能无法在在线IDE中运行。请使用离线IDE,并设置文件的名称