Files расширение файла java

Get real file extension -Java code

If you mean «real extension» based on the file contents then Magic numbers are a good place to start.

I think he is talking about the real file type. That means if you rename an EXE as a jpg he needs to detect it as an exe. Yes. Magic numbers are one of the possible ways.

For file extension, as in the bit at the end of the file name, you need to be very careful trusting input from untrusted sources (who’d have guessed). In particular trick such as inserting NUL character may circumvent your check.

3 Answers 3

Supposing you really mean to get the true content type of a file (ie it’s MIME type) you should refer to this excellent answer.

You can get the true content type of a file in Java using the following code:

File file = new File("filename.asgdsag"); InputStream is = new BufferedInputStream(new FileInputStream(file)); String mimeType = URLConnection.guessContentTypeFromStream(is); 

Also re-directed SO users with similar questions to that answer 🙂 It’s quite strange that URLConnection.guessContentTypeFromStream method is not well-known — a lot of resources advise to use third-party libraries, when the answer is right there in JDK .

There are a number of ways that you can do this, some more complicated (and more reliable) than others. The page I linked to discusses quite a few of these approaches.

Читайте также:  Расположить блок слева css

Not sure exactly what you mean, but however you do this it is only going to work for the specific set of file formats which are known to you

you could exclude executables (are you talking windows here?) — there’s some file header information here http://support.microsoft.com/kb/65122 — you could scan and block files which look like they have an exe header — is this getting close to what you mean when you say ‘real file extension’?

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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

Assuming I am given a URI, and I want to find the file extension of the file that is returned, what do I have to do in Java. For example the file at http://www.daml.org/2001/08/baseball/baseball-ont is http://www.daml.org/2001/08/baseball/baseball-ont.owl When I do

 URI uri = new URI(address); URL url = uri.toURL(); String file = url.getFile(); System.out.println(file); 

I am not able to see the full file name with .owl extension, just /2001/08/baseball/baseball-ont how do I get the file extension as well. «

8 Answers 8

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("."))

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.

Источник

Как получить расширение файла в Java

В наших реализациях будут возвращены символы после финального ‘.’.

Поэтому, в качестве быстрого примера, если имя нашего файлаjarvis.txt, тогда он вернетString «txt” в качестве расширения файла.

2. Получение расширения файла

Для каждого подхода мы узнаем, как его реализовать, и проследим, что происходит в двух особых случаях:

  • когда имя файла не имеет расширений, например файлmakefile
  • и если имя файла состоит только из расширения, например.gitignore или.DS_Store.

2.1. Простой подход к обработкеString

При таком подходе мы будем использовать простой подход обработкиString для поиска расширения:

public Optional getExtensionByStringHandling(String filename) < return Optional.ofNullable(filename) .filter(f ->f.contains(".")) .map(f -> f.substring(filename.lastIndexOf(".") + 1)); >

Этот метод проверяет наличие точки ‘. ‘ вхождение в заданном имени файла.

Если он существует, он найдет последнюю позицию точки ‘. ‘ и вернуть символы после этого, символы после последней точки ‘. ‘ известный как расширение файла.

Особые случаи:

  1. No extension — этот метод вернет пустойString
  2. Only extension — этот метод вернетString после точки, например “gitignore”

2.2. FilenameUtils.getExtension из Apache Commons IO

Во втором подходе мы найдем расширение, используя служебный класс, предоставляемый библиотекой ввода-вывода Apache Commons:

public String getExtensionByApacheCommonLib(String filename)

Здесь вместо имени файла мы также можем указать полный путь к файлуe.g. «C:/example/com/demo.java».

МетодgetExtension(String) проверит, является ли данныйfilename пустым или нет.

Еслиfilename пустое или нулевое значение,getExtension(String filename) вернет данный экземпляр. В противном случае он возвращает расширение имени файла.

Для этого он использует методindexOfExtension(String), который, в свою очередь, используетlastIndexof(char) для поиска последнего вхождения «.». Оба эти метода предоставляютсяFilenameUtils.

Этот метод также проверяет отсутствие разделителя каталогов после последней точки с помощью другого методаindexOfLastSeparator(String),, который будет обрабатывать файл в формате Unix или Windows.

Особые случаи:

  1. No extension — этот метод вернет пустую строку.
  2. Only extension — этот метод вернетString после точки, например “gitignore”

2.3. Использование библиотеки Guava

В этом последнем подходе мы будем использовать библиотеку Guava для поиска расширения.

Чтобы добавить библиотеку Guava, мы можем добавить следующую зависимость к нашемуpom.xml:

 com.google.guava guava 24.1.1-jre 

Для последней зависимости мы можем проверитьMaven Central.

После добавления библиотеки мы можем просто использовать ее методgetFileExtension:

public String getExtensionByGuava(String filename)

МетодgetFileExtension(String) сначала проверит, пуст ли данныйfilename.

Еслиfilename не пуст, то он создаст экземплярFile путем преобразования заданногоfilename в абстрактный путь и вызовет методFile’sgetName() поверх it, который вернет имя файла, обозначенного этим абстрактным путем, или пустую строку, если заданныйfilename пуст.

На основе этого возвращаемого значения выбирается индекс последнего появления символа «.» с помощью встроенного методаString классаlastIndexOf(char).

Особые случаи:

  1. Без расширения — этот метод вернет пустойString
  2. Только расширение — этот метод вернетString после точки, например “gitignore”

3. Заключение

При выборе между ApacheCommons иGuava, в то время как обе библиотеки имеют некоторые общие функции, а также функциональность, отсутствующую в их альтернативе.

Это означает, что если требуется определенная функциональность, выберите ту, которая имеет ее. В противном случае, если требуется больше пользовательских сценариев, выберите тот, который выполняет большинство ваших задач, и не стесняйтесь обернуть его собственной реализацией, чтобы получить желаемый результат.

Также ознакомьтесь со всеми примерами в этой статьеon Github.

Источник

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