String getName()
描述 (Description)
java.io.File.getName()方法返回路径名的序列的姓氏,这意味着返回由此抽象路径名表示的文件或目录的名称。
声明 (Declaration)
以下是java.io.File.getName()方法的声明 -
public String getName()
参数 (Parameters)
NA
返回值 (Return Value)
如果pathname的名称序列为空,则此方法返回文件或目录的名称或空字符串。
异常 (Exception)
NA
例子 (Example)
以下示例显示了java.io.File.getName()方法的用法。
package com.iowiki;
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
File f1 = null;
String v, v1;
boolean bool = false;
try {
// create new files
f = new File("C:\\test.txt");
f1 = new File("C:\\Program Files");
// get file name or directory name
v = f.getName();
v1 = f1.getName();
// true if the file path exists
bool = f.exists();
// if file exists
if(bool) {
// prints
System.out.println("File name: "+v);
}
// true if the directory exists
bool = f1.exists();
// if the folder exists
if(bool) {
// prints
System.out.print("Folder name: "+v1);
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生以下结果 -
File name: test.txt
Folder name: Program Files