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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024