Below is an example that can be used to get the extension of a file. The code below assume that the extension is the last part of the file name after the last dot symbol. For instance if you have a file named data.txt
the extension will be txt
, but if you have a file named data.tar.gz
the extension will be gz
.
package org.kodejava.io;
import java.io.File;
public class FileExtension {
private static final String EXT_SEPARATOR = ".";
public static void main(String[] args) {
File file = new File("data.txt");
String ext = FileExtension.getFileExtension(file);
System.out.println("Ext = " + ext);
file = new File("F:/Temp/Data/data.tar.gz");
ext = FileExtension.getFileExtension(file);
System.out.println("Ext = " + ext);
file = new File("F:/Temp/Data/HelloWorld.java");
ext = FileExtension.getFileExtension(file);
System.out.println("Ext = " + ext);
}
/**
* Get the extension of the specified file.
*
* @param file a file.
* @return the extension of the file.
*/
private static String getFileExtension(File file) {
if (file == null) {
return null;
}
String name = file.getName();
int extIndex = name.lastIndexOf(FileExtension.EXT_SEPARATOR);
if (extIndex == -1) {
return "";
} else {
return name.substring(extIndex + 1);
}
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023