如何在Java中获取文件扩展名

x33g5p2x  于2022-10-06 转载在 Java  
字(0.9k)|赞(0)|评价(0)|浏览(376)

在这个例子中,我们将检查文件扩展名,如txt, docx,pdf等。

获取文件扩展名示例

  1. 让我们使用String类的lastIndexOf()方法来查找最后一个字符". "的索引。
  2. 首先检查该文件是否有扩展名。
  3. 使用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

相关文章

微信公众号

最新文章

更多