How to Get the File Extension of a File in Java

How do I get the file extension of a file in Java?

In this case, use FilenameUtils.getExtension from Apache Commons IO

Here is an example of how to use it (you may specify either full path or just file name):

import org.apache.commons.io.FilenameUtils;

// ...

String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"

Maven dependency:

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

Gradle Groovy DSL

implementation 'commons-io:commons-io:2.6'

Gradle Kotlin DSL

implementation("commons-io:commons-io:2.6")

Others https://search.maven.org/artifact/commons-io/commons-io/2.6/jar

Is there a new Java 8 way of retrieving the file extension?

No, see the changelog of the JDK8 release

Get file extension from uploaded file

I have found the solution for this. Actually this is of Play framework. I got the file using following code.

MultipartFormData body = request().body().asMultipartFormData();
FilePart fileInput = body.getFile("fileInput");
File file = fileInput.getFile();

I tried to get the name of file using this File object (which is used to store in a tmp location). But I missed to notice that FilePart object contains all file details that was uploaded. Then I figured it out.

fileInput.getFilename() gives me the uploaded file name with extension. It solves my problem.

Thanks for Cataclysm for helping me out. Surely the one he gave is the best answer for other framework like Struts/Spring or core servlets.

How to check the File Type in java

You may use Files Utility of Guava , and use the method of Files.getFileExtension(String String fullName)

System.out.println(Files.getFileExtension("C:\\fileName.txt"));

The output is:

txt

The source code is pretty simple though,

public static String getFileExtension(String fullName) {
checkNotNull(fullName);
String fileName = new File(fullName).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}

How to get the file extension in Android?

lots of ways . here are 2 sample-

String someFilepath = "image.fromyesterday.test.jpg"; 
String extension = someFilepath.substring(someFilepath.lastIndexOf("."));

So in you case, it should be something like that

String extension = ff.getAbsolutePath().substring(ff.getAbsolutePath().lastIndexOf("."));

In case if you don't want to do it yourself-

use FilenameUtils.getExtension from Apache Commons IO-

String extension = FilenameUtils.getExtension("/path/to/file/mytext.txt");

or in your case -

String extension = FilenameUtils.getExtension(ff.getAbsolutePath());

How to determine the file extension of a file from a uri

At first, I want to make sure you know it's impossible to find out what kind of file a URI links too, since a link ending with .jpg might let you access a .exe file (this is especially true for URL's, due to symbolic links and .htaccess files), thus it isn't a rock solid solution to fetch the real extension from the URI if you want to limit allowed file types, if this is what you're going for of course. So, I assume you just want to know what extension a file has based on it's URI even though this isn't completely trustworthy;

You can get the extension from any URI, URL or file path using the method bellow. You don't have to use any libraries or extensions, since this is basic Java functionality. This solution get's the position of the last . (period) sign in the URI string, and creates a sub-string starting at the position of the period sign, ending at the end of the URI string.

String uri = "http://www.google.com/support/enterprise/static/gsa/docs/admin/70/gsa_doc_set/integrating_apps/images/google_logo.png";
String extension = uri.substring(uri.lastIndexOf("."));

This code sample will above will output the .png extension from the URI in the extension variable, note that a . (period) is included in the extension, if you want to gather the file extension without a prefixed period, increase the substring index by one, like this:

String extension = uri.substring(url.lastIndexOf(".") + 1);

One pro for using this method over regular expressions (a method other people use a lot) is that this is a lot less resource expensive and a lot less heavy to execute while giving the same result.

Additionally, you might want to make sure the URL contains a period character, use the following code to achieve this:

String uri = "http://www.google.com/support/enterprise/static/gsa/docs/admin/70/gsa_doc_set/integrating_apps/images/google_logo.png";
if(uri.contains(".")) {
String extension = uri.substring(url.lastIndexOf("."));
}

You might want to improve the functionally even further to create a more robust system. Two examples might be:

  • Validate the URI by checking it exists, or by making sure the syntax of the URI is valid, possibly using a regular expression.
  • Trim the extension to remove unwanted white spaces.

I won't cover the solutions for these two features in here, because that isn't what was being asked in the first place.

Hope this helps!

Java - Count all file extensions in a folder using DirectoryStream

First check whether it is a file, if so extract the file name extension. Finally use the groupingBy collector to get the dictionary structure you want. Here's how it looks.

try (Stream<Path> stream = Files.list(Paths.get("path/to/your/file"))) {
Map<String, Long> fileExtCountMap = stream.filter(Files::isRegularFile)
.map(f -> f.getFileName().toString().toUpperCase())
.map(n -> n.substring(n.lastIndexOf(".") + 1))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}

Java: A way to match Mime (content) type to file extension from CommonsMultipartFile

Java library for that case is quite limited (number of types). This is how I do it:

static String getMimeType(String fileName) {
// 1. first use java's built-in utils
FileNameMap mimeTypes = URLConnection.getFileNameMap();
String contentType = mimeTypes.getContentTypeFor(fileName);

// 2. nothing found -> lookup our in extension map to find types like ".doc" or ".docx"
if (contentType == null) {
String extension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length());;
contentType = fileExtensionMap.get(extension);
}
return contentType;
}

step 2 involves having a static map:

private static final Map<String, String> fileExtensionMap;

static {
fileExtensionMap = new HashMap<String, String>();
// MS Office
fileExtensionMap.put("doc", "application/msword");
fileExtensionMap.put("dot", "application/msword");
fileExtensionMap.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
fileExtensionMap.put("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
fileExtensionMap.put("docm", "application/vnd.ms-word.document.macroEnabled.12");
fileExtensionMap.put("dotm", "application/vnd.ms-word.template.macroEnabled.12");
fileExtensionMap.put("xls", "application/vnd.ms-excel");
fileExtensionMap.put("xlt", "application/vnd.ms-excel");
fileExtensionMap.put("xla", "application/vnd.ms-excel");
fileExtensionMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
fileExtensionMap.put("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
fileExtensionMap.put("xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
fileExtensionMap.put("xltm", "application/vnd.ms-excel.template.macroEnabled.12");
fileExtensionMap.put("xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
fileExtensionMap.put("xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
fileExtensionMap.put("ppt", "application/vnd.ms-powerpoint");
fileExtensionMap.put("pot", "application/vnd.ms-powerpoint");
fileExtensionMap.put("pps", "application/vnd.ms-powerpoint");
fileExtensionMap.put("ppa", "application/vnd.ms-powerpoint");
fileExtensionMap.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
fileExtensionMap.put("potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
fileExtensionMap.put("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
fileExtensionMap.put("ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
fileExtensionMap.put("pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
fileExtensionMap.put("potm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
fileExtensionMap.put("ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
// Open Office
fileExtensionMap.put("odt", "application/vnd.oasis.opendocument.text");
fileExtensionMap.put("ott", "application/vnd.oasis.opendocument.text-template");
fileExtensionMap.put("oth", "application/vnd.oasis.opendocument.text-web");
fileExtensionMap.put("odm", "application/vnd.oasis.opendocument.text-master");
fileExtensionMap.put("odg", "application/vnd.oasis.opendocument.graphics");
fileExtensionMap.put("otg", "application/vnd.oasis.opendocument.graphics-template");
fileExtensionMap.put("odp", "application/vnd.oasis.opendocument.presentation");
fileExtensionMap.put("otp", "application/vnd.oasis.opendocument.presentation-template");
fileExtensionMap.put("ods", "application/vnd.oasis.opendocument.spreadsheet");
fileExtensionMap.put("ots", "application/vnd.oasis.opendocument.spreadsheet-template");
fileExtensionMap.put("odc", "application/vnd.oasis.opendocument.chart");
fileExtensionMap.put("odf", "application/vnd.oasis.opendocument.formula");
fileExtensionMap.put("odb", "application/vnd.oasis.opendocument.database");
fileExtensionMap.put("odi", "application/vnd.oasis.opendocument.image");
fileExtensionMap.put("oxt", "application/vnd.openofficeorg.extension");
// Other
fileExtensionMap.put("txt", "text/plain");
fileExtensionMap.put("rtf", "application/rtf");
fileExtensionMap.put("pdf", "application/pdf");
}

works fine for me, hope that helps!



Related Topics



Leave a reply



Submit