获取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));
}热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短