获取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 妈妈生日祝福语简短励志