Java know file extension

Java Program to Get the File Extension

To understand this example, you should have the knowledge of the following Java programming topics:

Example 1: Java Program to get the file extension

import java.io.File; class Main < public static void main(String[] args) < File file = new File("Test.java"); // convert the file name into string String fileName = file.toString(); int index = fileName.lastIndexOf('.'); if(index >0) < String extension = fileName.substring(index + 1); System.out.println("File extension is " + extension); >> >
  • file.toString() — Converts the File object into a string.
  • fileName.lastIndexOf(‘.’) — Returns the last occurrence of character. Since all file extension starts with ‘.’, we use the character ‘.’.
  • fileName.substring() — Returns the string after character ‘.’.

Example 2: Get the file extension of all files present in a directory

Now, suppose we want to get the file extension of all the files present in a directory. We can use the above process in the loop.

import java.io.File; class Main < public static void main(String[] args) < File directory = new File("Directory"); // list all files present in the directory File[] files = directory.listFiles(); System.out.println("Files\t\t\tExtension"); for(File file : files) < // convert the file name into string String fileName = file.toString(); int index = fileName.lastIndexOf('.'); if(index >0) < String extension = fileName.substring(index + 1); System.out.println(fileName + "\t" + extension); >> > >
Files Extension Directory\file1.txt txt Directory\file2.svg svg Directory\file3.java java Directory\file4.py py Directory\file5.html html

Note: The output of the program depends on the directory you use and the files in the directory.

    If you are using the Gauva Library, you can directly use the getFileExtension() method to get the file extension. For example,

String fileName = "Test.java"; String extension = Files.getFileExtension(fileName);
String extension = FilenameUtils.getExtension("file.py") // returns py

Источник

Get File Extension in Java

Get File Extension in Java | Here we will discuss how to get file extension in Java using different classes and libraries. We can either take the help of external Java libraries or we can develop our own logic to get the file extension in Java. For this, first, we will create a file object using the Java File class.

Читайте также:  Php get file open error

Example-1:-
File name = “Test.txt”
Extension of file = “txt”

Example-2:-
File name = “maven-3.8.6-settings.xml”
Extension of file = “xml”

Program to Get File Extension in Java using lastIndexOf() & substring()

To get the file extension we can take the help of the lastIndexOf() method of the Java String class. In a given file, we can identify extensions using the dot (‘.’) character. Example:- image.png, here “png” is the file extension, and “image” is the file name.

We should be using lastIndexOf() method instead of indexOf() method because there can be case where fileName also contains dot (‘.’) character. For example:- “maven-3.8.6-settings.xml”. The lastIndexOf() method of the String class returns the last index of the given character in the given string, and if the character doesn’t exist in the given string then it returns -1.

After getting the last index of the dot (‘.’) character, we can call the substring() method to get the substring from index+1 to the end of the string. Later we will convert the result to lowercase using the toLowerCase() method.

import java.io.File; public class Main < private static String getExtension(String fileName) < if (fileName == null) < return null; >int lastDotIndex = fileName.lastIndexOf('.'); return (lastDotIndex == -1) ? "" : fileName.substring(lastDotIndex + 1).toLowerCase(); > public static void main(String[] args) < File file = new File("Test.txt"); String fileName = file.toString(); String extension = getExtension(fileName); System.out.println("File name: " + fileName); System.out.println("Extension: " + extension); File file1 = new File("/home/user/Downloads/maven-3.8.6-settings.xml"); System.out.println("Extension: " + getExtension(file1.toString())); File file2 = new File("Hello-World"); System.out.println("Extension: " + getExtension(file2.toString())); >>

File name: Test.txt
Extension: txt
Extension: xml
Extension:

It will return the file extension without the dot “.”. Example:- file = “Test.txt” then it return “txt”. If you want to include the dot (‘.’) in file extension then we have to call fileName.substring(lastDotIndex).

return (lastDotIndex == -1) ? "" : fileName.substring(lastDotIndex).toLowerCase();

The same program can be written with the help of Java Stream as follows. Program to get file extension in Java with the help of Stream API:-

import java.io.File; import java.util.Optional; public class Main < private static OptionalgetExtension(String fileName) < return Optional.ofNullable(fileName).filter(f ->f.contains(".")) .map(f -> f.substring(fileName.lastIndexOf(".") + 1)); > public static void main(String[] args) < File file = new File("Test.txt"); String extension = getExtension(file.toString()).get(); System.out.println("Extension: " + extension); >>

Get File Extension in Java using Apache Commons IO

The Apache Commons IO contains FilenameUtils class which provides multiple methods for general file name and file path manipulation utilities. It has the getExtension() method which returns the extension of the given file.

Method syntax:- public static String getExtension(String fileName) throws IllegalArgumentException

The getExtension() method of FilenameUtils class of org.apache.commons.io returns the textual part of the fileName after the last dot. There must be no directory separator after the dot. It throws IllegalArgumentException in windows for file names like “foo.exe:bar.txt”.

import java.io.File; import org.apache.commons.io.FilenameUtils; public class Main < public static void main(String[] args) < File file = new File("app-request.json"); System.out.println("Extension: " + FilenameUtils.getExtension(file.toString())); >>

Get File Extension in Java using Guava Library

By using Guava libraries (Guava: Google Core Libraries for Java), we can get the file extension. The Files class of Guava libraries contains the getFileExtension() method. Method syntax:- public static String getFileExtension​(String fullName)

Читайте также:  Java naming and directory interface jndi

It returns the file extension for the given file name, or the empty string if the file has no extension. The result does not include the ‘.’.

import java.io.File; import com.google.common.io.Files; public class Main < public static void main(String[] args) < File file = new File("script.py"); System.out.println("Extension: " + Files.getFileExtension(file.toString())); >>

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Get the File Extension of a File in Java

Get the File Extension of a File in Java

  1. Get the File Extension Using the getExtension() Method in Java
  2. Get the File Extension of a File With the lastIndexOf() Method in Java
  3. Get the File Extension of a File With String Parsing in Java
  4. Get the File Extension of a File Using the replaceAll() Method in Java
  5. Get the File Extension of a File Using contains() and lastIndexOf() Method in Java
  6. Get the File Extension of a File Using ternary operators in Java
  7. Get the File Extension of a File Using stream() Method in Java
  8. Get the File Extension of a File Using Regex in Java

This tutorial introduces how to get the file extension of a file in Java.

Get the File Extension Using the getExtension() Method in Java

To get an extension of a file, we can use the getExtension() method of the FilenameUtils class. This method returns the extension of the file. Since this method belongs to Apache commons library, you must download the library from Apache official site to use JARs in your project.

import org.apache.commons.io.FilenameUtils;  public class SimpleTesting   public static void main(String[] args)  String fileName = "student-records.pdf";  String fe = FilenameUtils.getExtension(fileName);  System.out.println("File extension is : "+fe);  > > 

Get the File Extension of a File With the lastIndexOf() Method in Java

If you don’t want to use any built-in method then use the given code example that uses lastIndexOf() method to get the file extension. It is the simplest and easy way that involves only string methods. See the example below.

public class SimpleTesting   public static void main(String[] args)  String fileName = "student-records.pdf";  String fe = "";  int i = fileName.lastIndexOf('.');  if (i > 0)   fe = fileName.substring(i+1);  >  System.out.println("File extension is : "+fe);  > > 

Get the File Extension of a File With String Parsing in Java

This is another solution that includes several scenarios including the one (if dot(.) is in the file path). This method returns the accurate result even if the file path has a dot(.) in between the file path. See the example below.

public class SimpleTesting   public static void main(String[] args)  String fileName = "folder\s.gr\fg\student-records.pdf";  String fe = "";  char ch;  int len;  if(fileName==null || (len = fileName.length())==0 || (ch = fileName.charAt(len-1))=='/' || ch=='\\' ||ch=='.' )   fe = "";  >  int dotInd = fileName.lastIndexOf('.'), sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));  if( dotInd  sepInd )   fe = "";  >  else   fe = fileName.substring(dotInd+1).toLowerCase();  >  System.out.println("File extension is : "+fe);  > > 

Get the File Extension of a File Using the replaceAll() Method in Java

We can use replaceAll() method to get file extension as we did in the below example. We use regular expression in this method and collect the result into a variable.

public class SimpleTesting   public static void main(String[] args)  String fileName = "folder\s.gr\fg\student-records.pdf";  String fe = "";  fe = fileName.replaceAll("^.*\\.(.*)$", "$1");  System.out.println("File extension is : "+fe);  > > 

Get the File Extension of a File Using contains() and lastIndexOf() Method in Java

The contains() method is used to check whether the specified char is present in the string or not and the lastIndexOf() method returns an index value of the specified char which is passed into substring() method to get file extension. We use these methods in this code to get file extension. See the example below.

public class SimpleTesting   public static void main(String[] args)  String fileName = "folder\s.gr\fg\student-records.pdf";  String fe = "";  if (fileName.contains("."))  fe = fileName.substring(fileName.lastIndexOf(".")+1);  System.out.println("File extension is : "+fe);  > > 

Get the File Extension of a File Using ternary operators in Java

If you are comfortable with ternary operators( ?, : ) then use it with substring() and lastIndexOf() method. It reduces the line of code and returns the result in a single statement.

public class SimpleTesting   public static void main(String[] args)  String fileName = "folder\s.gr\fg\student-records.pdf";  String fe = "";  if (fileName.contains("."))   int i = fileName.lastIndexOf('.');  fe = i > 0 ? fileName.substring(i + 1) : "";  >  System.out.println("File extension is : "+fe);  > > 

Get the File Extension of a File Using stream() Method in Java

We can use stream() method of Arrays class to convert the file name into stream and use split() method to break the file name from the dot( . ). See the example below.

import java.util.Arrays; public class SimpleTesting   public static void main(String[] args)  String fileName = "folder\s.gr\fg\student-records.pdf";  String fe = "";  if (fileName.contains("."))   fe = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null);  >  System.out.println("File extension is : "+fe);  > > 

Get the File Extension of a File Using Regex in Java

This is another solution that uses regex package. The compile() and matcher() method of Pattern class is used to fetch extension of the file in this Java example. See the example below.

import java.util.regex.Matcher; import java.util.regex.Pattern; public class SimpleTesting   public static void main(String[] args)  String fileName = "folder\s.gr\fg\student-records.pdf";  String fe = "";  final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)");  Matcher m = PATTERN.matcher(fileName);  if (m.find())   fe = m.group(2);  >  System.out.println("File extension is : "+fe);  > > 

Related Article — Java IO

Related Article — Java File

Источник

Оцените статью