Java File getName()方法及示例

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

Java中的文件getName方法及示例

例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

Java中的文件getName方法及示例

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程