Comment obtenir l'extension de fichier d'un fichier en Java?


Juste pour être clair, je ne cherche pas le type MIME.

Disons que j'ai l'entrée suivante: /path/to/file/foo.txt

Je voudrais un moyen de diviser cette entrée, spécifiquement en .txt pour l'extension. Existe-t-il un moyen intégré de le faire en Java? Je voudrais éviter d'écrire mon propre analyseur.

Author: longda, 2010-08-26

27 answers

Dans ce cas, utilisez FilenameUtils.getExtension à partir de Apache Commons IO

Voici un exemple de comment l'utiliser (vous pouvez spécifier le chemin complet ou simplement le nom du fichier):

String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"
 519
Author: Juan Rojas, 2016-10-11 15:05:41

Avez-vous vraiment besoin d'un" analyseur " pour cela?

String extension = "";

int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}

En supposant que vous avez affaire à des noms de fichiers simples de type Windows, pas à quelque chose comme archive.tar.gz.

Btw, pour le cas où un répertoire peut avoir un '.', mais le nom de fichier lui-même ne le fait pas (comme /path/to.a/file), vous pouvez faire

String extension = "";

int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));

if (i > p) {
    extension = fileName.substring(i+1);
}
 250
Author: EboMike, 2013-05-30 08:11:32
private String getFileExtension(File file) {
    String name = file.getName();
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf);
}
 76
Author: spectre, 2018-08-09 23:05:29

Si vous utilisez Goyave bibliothèque, vous pouvez recourir à Files classe utilitaire. Il a une méthode spécifique, getFileExtension(). Par exemple:

String path = "c:/path/to/file/foo.txt";
String ext = Files.getFileExtension(path);
System.out.println(ext); //prints txt

En outre, vous pouvez également obtenir le nom de fichier avec une fonction similaire, getNameWithoutExtension():

String filename = Files.getNameWithoutExtension(path);
System.out.println(filename); //prints foo
 72
Author: JeanValjean, 2017-04-19 19:57:45

Si sur Android, vous pouvez utiliser ceci:

String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());
 28
Author: intrepidis, 2016-01-29 19:55:36

Afin de prendre en compte les noms de fichiers sans caractères avant le point, vous devez utiliser cette légère variation de la réponse acceptée:

String extension = "";

int i = fileName.lastIndexOf('.');
if (i >= 0) {
    extension = fileName.substring(i+1);
}

"file.doc" => "doc"
"file.doc.gz" => "gz"
".doc" => "doc"
 15
Author: Sylvain Leroux, 2013-09-11 13:07:53

Mon sale et peut le plus petit en utilisant Chaîne.Remplacez tout :

.replaceAll("^.*\\.(.*)$", "$1")

Notez que le premier * est gourmand, il va donc saisir la plupart des caractères possibles autant que possible, puis juste le dernier point et l'extension de fichier seront laissés.

 9
Author: Ebrahim Byagowi, 2014-03-13 23:59:53

Ceci est une méthode testée

public static String getExtension(String fileName) {
    char ch;
    int len;
    if(fileName==null || 
            (len = fileName.length())==0 || 
            (ch = fileName.charAt(len-1))=='/' || ch=='\\' || //in the case of a directory
             ch=='.' ) //in the case of . or ..
        return "";
    int dotInd = fileName.lastIndexOf('.'),
        sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
    if( dotInd<=sepInd )
        return "";
    else
        return fileName.substring(dotInd+1).toLowerCase();
}

Et cas de test:

@Test
public void testGetExtension() {
    assertEquals("", getExtension("C"));
    assertEquals("ext", getExtension("C.ext"));
    assertEquals("ext", getExtension("A/B/C.ext"));
    assertEquals("", getExtension("A/B/C.ext/"));
    assertEquals("", getExtension("A/B/C.ext/.."));
    assertEquals("bin", getExtension("A/B/C.bin"));
    assertEquals("hidden", getExtension(".hidden"));
    assertEquals("dsstore", getExtension("/user/home/.dsstore"));
    assertEquals("", getExtension(".strange."));
    assertEquals("3", getExtension("1.2.3"));
    assertEquals("exe", getExtension("C:\\Program Files (x86)\\java\\bin\\javaw.exe"));
}
 7
Author: yavuzkavus, 2016-03-29 11:37:02

Que diriez-vous (en utilisant Java 1.5 RegEx):

    String[] split = fullFileName.split("\\.");
    String ext = split[split.length - 1];
 6
Author: Ninju Bohra, 2013-04-10 18:21:32

Si vous prévoyez d'utiliser Apache commons-io, et que vous voulez juste vérifier l'extension du fichier, puis faire une opération,vous pouvez utiliser this , voici un extrait:

if(FilenameUtils.isExtension(file.getName(),"java")) {
    someoperation();
}
 6
Author: Geng Jiawen, 2014-06-10 10:41:26

Comme il ressort de toutes les autres réponses, il n'y a pas de fonction "intégrée" adéquate. C'est le moyen sûr et simple de la méthode.

String getFileExtension(File file) {
    if (file == null) {
        return "";
    }
    String name = file.getName();
    int i = name.lastIndexOf('.');
    String ext = i > 0 ? name.substring(i + 1) : "";
    return ext;
}
 5
Author: intrepidis, 2018-02-15 02:08:52

Que diriez-vous de JFileChooser? Ce n'est pas simple car vous devrez analyser sa sortie finale...

JFileChooser filechooser = new JFileChooser();
File file = new File("your.txt");
System.out.println("the extension type:"+filechooser.getTypeDescription(file));

Qui est un type MIME...

OK...J'oublie que vous ne voulez pas connaître son type MIME.

Code intéressant dans le lien suivant: http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

/*
 * Get the extension of a file.
 */  
public static String getExtension(File f) {
    String ext = null;
    String s = f.getName();
    int i = s.lastIndexOf('.');

    if (i > 0 &&  i < s.length() - 1) {
        ext = s.substring(i+1).toLowerCase();
    }
    return ext;
}

Question connexe: Comment couper une extension de fichier à partir d'une chaîne en Java?

 4
Author: eee, 2017-05-23 12:10:48

Voici une méthode qui gère correctement .tar.gz, même dans un chemin avec des points dans les noms de répertoire:

private static final String getExtension(final String filename) {
  if (filename == null) return null;
  final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1);
  final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1;
  final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash);
  return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1);
}

afterLastSlash est créé pour rendre la recherche afterLastBackslash plus rapide car il n'aura pas à rechercher toute la chaîne s'il y a des barres obliques.

Le char[] à l'intérieur du Stringoriginal est réutilisé, n'y ajoutant aucune poubelle, et la JVM remarquera probablement que afterLastSlash est immédiatement poubelle afin de le mettre sur la pile au lieu du tas.

 4
Author: Olathe, 2013-04-14 12:07:01

Voici la version avec Optional comme valeur de retour (car vous ne pouvez pas être sûr que le fichier a une extension)... aussi des contrôles de santé mentale...

import java.io.File;
import java.util.Optional;

public class GetFileExtensionTool {

    public static Optional<String> getFileExtension(File file) {
        if (file == null) {
            throw new NullPointerException("file argument was null");
        }
        if (!file.isFile()) {
            throw new IllegalArgumentException("getFileExtension(File file)"
                    + " called on File object that wasn't an actual file"
                    + " (perhaps a directory or device?). file had path: "
                    + file.getAbsolutePath());
        }
        String fileName = file.getName();
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            return Optional.of(fileName.substring(i + 1));
        } else {
            return Optional.empty();
        }
    }
}
 2
Author: schuttek, 2017-02-17 20:56:00
// Modified from EboMike's answer

String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));

L'extension devrait avoir ".txt " en elle lors de l'exécution.

 1
Author: longda, 2010-08-26 01:32:46
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");
 1
Author: Alfaville, 2015-05-24 14:59:17

Ici, j'ai fait une petite méthode (mais pas si sécurisée et ne vérifie pas beaucoup d'erreurs), mais si c'est seulement vous qui programmez un programme java général, c'est plus que suffisant pour trouver le type de fichier. Cela ne fonctionne pas pour les types de fichiers complexes, mais ceux-ci ne sont normalement pas utilisés autant.

    public static String getFileType(String path){
       String fileType = null;
       fileType = path.substring(path.indexOf('.',path.lastIndexOf('/'))+1).toUpperCase();
       return fileType;
}
 1
Author: Rivalion, 2015-06-15 21:53:52

Obtenir l'extension de fichier à partir du nom de fichier

/**
 * The extension separator character.
 */
private static final char EXTENSION_SEPARATOR = '.';

/**
 * The Unix separator character.
 */
private static final char UNIX_SEPARATOR = '/';

/**
 * The Windows separator character.
 */
private static final char WINDOWS_SEPARATOR = '\\';

/**
 * The system separator character.
 */
private static final char SYSTEM_SEPARATOR = File.separatorChar;

/**
 * Gets the extension of a filename.
 * <p>
 * This method returns the textual part of the filename after the last dot.
 * There must be no directory separator after the dot.
 * <pre>
 * foo.txt      --> "txt"
 * a/b/c.jpg    --> "jpg"
 * a/b.txt/c    --> ""
 * a/b/c        --> ""
 * </pre>
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename the filename to retrieve the extension of.
 * @return the extension of the file or an empty string if none exists.
 */
public static String getExtension(String filename) {
    if (filename == null) {
        return null;
    }
    int index = indexOfExtension(filename);
    if (index == -1) {
        return "";
    } else {
        return filename.substring(index + 1);
    }
}

/**
 * Returns the index of the last extension separator character, which is a dot.
 * <p>
 * This method also checks that there is no directory separator after the last dot.
 * To do this it uses {@link #indexOfLastSeparator(String)} which will
 * handle a file in either Unix or Windows format.
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename  the filename to find the last path separator in, null returns -1
 * @return the index of the last separator character, or -1 if there
 * is no such character
 */
public static int indexOfExtension(String filename) {
    if (filename == null) {
        return -1;
    }
    int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
    int lastSeparator = indexOfLastSeparator(filename);
    return (lastSeparator > extensionPos ? -1 : extensionPos);
}

/**
 * Returns the index of the last directory separator character.
 * <p>
 * This method will handle a file in either Unix or Windows format.
 * The position of the last forward or backslash is returned.
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename  the filename to find the last path separator in, null returns -1
 * @return the index of the last separator character, or -1 if there
 * is no such character
 */
public static int indexOfLastSeparator(String filename) {
    if (filename == null) {
        return -1;
    }
    int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
    int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
    return Math.max(lastUnixPos, lastWindowsPos);
}

Crédits

  1. Copié à partir de la classe Apache FileNameUtils - http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/1.3.2/org/apache/commons/io/FilenameUtils.java#FilenameUtils.getExtension%28java.lang.String%29
 1
Author: Vasanth, 2016-11-18 08:36:14

Que diriez-vous deREGEX version:

static final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)");

Matcher m = PATTERN.matcher(path);
if (m.find()) {
    System.out.println("File path/name: " + m.group(1));
    System.out.println("Extention: " + m.group(2));
}

Ou avec l'extension null prise en charge:

static final Pattern PATTERN =
    Pattern.compile("((.*\\" + File.separator + ")?(.*)(\\.(.*)))|(.*\\" + File.separator + ")?(.*)");

class Separated {
    String path, name, ext;
}

Separated parsePath(String path) {
    Separated res = new Separated();
    Matcher m = PATTERN.matcher(path);
    if (m.find()) {
        if (m.group(1) != null) {
            res.path = m.group(2);
            res.name = m.group(3);
            res.ext = m.group(5);
        } else {
            res.path = m.group(6);
            res.name = m.group(7);
        }
    }
    return res;
}


Separated sp = parsePath("/root/docs/readme.txt");
System.out.println("path: " + sp.path);
System.out.println("name: " + sp.name);
System.out.println("Extention: " + sp.ext);

Résultat pour *nix:
chemin d'accès: /root/docs/
nom: lisez-moi
Extension: txt

Pour Windows, parsePath("c:\windows\readme.txt"):
chemin d'accès: c:\windows\
nom: lisez-moi
Extension: txt

 1
Author: Dmitry Sokolyuk, 2017-03-28 10:49:13

Sans utiliser de bibliothèque, vous pouvez utiliser la méthode String split comme suit:

        String[] splits = fileNames.get(i).split("\\.");

        String extension = "";

        if(splits.length >= 2)
        {
            extension = splits[splits.length-1];
        }
 1
Author: Farah, 2017-06-23 01:33:07
path = "/Users/test/test.txt"

extension = path.substring(path.lastIndexOf("."), path.length());

Retour ".txt "

Si vous voulez seulement "txt", faire path.lastIndexOf(".") + 1

 1
Author: Clément Chameyrat, 2017-08-24 15:57:32

Juste une alternative basée sur une expression régulière. Pas si vite, pas si bien que ça.

Pattern pattern = Pattern.compile("\\.([^.]*)$");
Matcher matcher = pattern.matcher(fileName);

if (matcher.find()) {
    String ext = matcher.group(1);
}
 0
Author: serhiy.h, 2013-05-13 12:38:39

Cette question particulière me pose beaucoup de problèmes, alors j'ai trouvé une solution très simple à ce problème que je poste ici.

file.getName().toLowerCase().endsWith(".txt");

C'est tout.

 0
Author: vikram Bhardwaj, 2016-04-24 08:11:29

J'ai trouvé un meilleur moyen de trouver une extension en mélangeant toutes les réponses ci-dessus

public static String getFileExtension(String fileLink) {

        String extension;
        Uri uri = Uri.parse(fileLink);
        String scheme = uri.getScheme();
        if (scheme != null && scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = mime.getExtensionFromMimeType(CoreApp.getInstance().getContentResolver().getType(uri));
        } else {
            extension = MimeTypeMap.getFileExtensionFromUrl(fileLink);
        }

        return extension;
    }

public static String getMimeType(String fileLink) {
        String type = CoreApp.getInstance().getContentResolver().getType(Uri.parse(fileLink));
        if (!TextUtils.isEmpty(type)) return type;
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getMimeTypeFromExtension(FileChooserUtil.getFileExtension(fileLink));
    }
 0
Author: Raghav Satyadev, 2018-01-15 06:08:37

Essayez ceci.

String[] extension = "adadad.adad.adnandad.jpg".split("\\.(?=[^\\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg
 -1
Author: Adnane, 2017-11-08 10:41:01
  @Test
    public void getFileExtension(String fileName){
      String extension = null;
      List<String> list = new ArrayList<>();
      do{
          extension =  FilenameUtils.getExtension(fileName);
          if(extension==null){
              break;
          }
          if(!extension.isEmpty()){
              list.add("."+extension);
          }
          fileName = FilenameUtils.getBaseName(fileName);
      }while (!extension.isEmpty());
      Collections.reverse(list);
      System.out.println(list.toString());
    }
 -1
Author: Ashish Pancholi, 2018-01-11 09:42:58

Java a une façon intégrée de gérer cela, dans le java.nio.fichier.Classe de fichiers , qui peut fonctionner pour vos besoins:

File f = new File("/path/to/file/foo.txt");
String ext = Files.probeContentType(f.toPath());
if(ext.equalsIgnoreCase("txt")) do whatever;

Notez que cette méthode statique utilise les spécifications trouvées ici pour récupérer le "type de contenu", qui peut varier.

 -4
Author: Nick Giampietro, 2013-09-25 20:47:06