获取Java中的文件扩展名
文件扩展名是计算机文件所附的后缀,它表示文件的格式。给出了演示获取文件扩展名的程序,如下所示:
示例
import java.io.File;
public class Demo {
private static String fileExtension(File file) {
String name = file.getName();
if(name.lastIndexOf(".") != -1 && name.lastIndexOf(".") != 0)
return name.substring(name.lastIndexOf(".") + 1);
else
return "";
}
public static void main(String[] args) {
File file = new File("demo1.txt");
System.out.println("The file extension is: " + fileExtension(file));
}
}上面程序的输出如下-
输出结果
The file extension is: txt
现在让我们了解上面的程序。
该方法fileExtension()返回文件扩展名,并且采用单个参数,即File类对象。证明这一点的代码片段如下-
private static String fileExtension(File file) {
String name = file.getName();
if(name.lastIndexOf(".") != -1 && name.lastIndexOf(".") != 0)
return name.substring(name.lastIndexOf(".") + 1);
else
return "";
}该方法main()调用该方法fileExtension()并打印返回的文件扩展名。证明这一点的代码片段如下所示-
public static void main(String[] args) {
File file = new File("demo1.txt");
System.out.println("The file extension is: " + fileExtension(file));
}