在这个例子中,我们将检查文件扩展名,如txt, docx,pdf
等。
lastIndexOf()
方法来查找最后一个字符". "的索引。substring()
方法来获取文件的扩展名。package com.javaguides.javaio.fileoperations.fileexamples;
import java.io.File;
/**
* This Java program demonstrates how to get file extension in Java example.
* @author javaguides.net
*/
public class GetFileExtensionExample {
private static String getFileExtension(File file) {
String fileName = file.getName();
if (fileName.lastIndexOf('.') != -1 && fileName.lastIndexOf('.') != 0) {
return fileName.substring(fileName.lastIndexOf('.') + 1);
} else {
return "File don't have extension";
}
}
public static void main(String[] args) {
File file = new File("sample.txt");
System.out.println(getFileExtension(file));
File file1 = new File("sample");
System.out.println(getFileExtension(file1));
File file2 = new File("sample.docx");
System.out.println(getFileExtension(file2));
}
}
上述程序的输出是。
txt
File don't have extension
docx
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/07/how-to-get-file-extension-in-java.html
内容来源于网络,如有侵权,请联系作者删除!