Comment puis-je obtenir l'extension 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

j'aimerais trouver un moyen de décomposer cette entrée, spécifiquement en .txt pour l'extension. Y a-t-il une manière de faire cela à Java? Je voudrais éviter d'écrire mon propre analyseur.

365
demandé sur longda 2010-08-26 04:19:38

27 réponses

dans ce cas, utilisez FilenameUtils.getExtension de Apache Commons IO

voici un exemple de la façon de l'utiliser (vous pouvez spécifier soit le chemin complet ou juste le nom du fichier):

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

avez-vous vraiment besoin d'un "parser" pour cela?

String extension = "";

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

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

Btw, pour le cas que d'un répertoire peut avoir un".', mais le nom du fichier lui-même ne 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
répondu 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
répondu spectre 2018-08-09 23:05:29

si vous utilisez Guava bibliothèque, vous pouvez recourir à Files classe d'utilité. 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
répondu JeanValjean 2017-04-19 19:57:45

si sur Android, vous pouvez utiliser ceci:

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

afin de tenir compte des 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
répondu Sylvain Leroux 2013-09-11 13:07:53

Mon sale et peut minuscules à l'aide de de la Chaîne.remplacer par

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

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

9
répondu Ebrahim Byagowi 2014-03-13 23:59:53

il s'agit d'une méthode éprouvé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 caisse d'essai:

@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
répondu yavuzkavus 2016-03-29 11:37:02

(à l'aide de Java 1.5 (RegEx):

    String[] split = fullFileName.split("\.");
    String ext = split[split.length - 1];
6
répondu 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 et ensuite faire une opération, vous pouvez utiliser ce , voici un extrait:

if(FilenameUtils.isExtension(file.getName(),"java")) {
    someoperation();
}
6
répondu 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
répondu intrepidis 2018-02-15 02:08:52

et JFileChooser? Il n'est pas simple car vous aurez besoin de parser sa production 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 tu ne veux 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
répondu eee 2017-05-23 12:10:48

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

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 slashes.

le char[] à l'intérieur du String original est réutilisé, n'y ajoutant aucun déchet, et le JVM remarquera probablement que afterLastSlash est immédiatement des ordures pour les mettre sur la pile au lieu du tas .

4
répondu Olathe 2013-04-14 12:07:01

Voici la version avec option comme valeur de retour (parce que vous ne pouvez pas être sûr que le fichier a une extension)... également des contrôles d'intégrité...

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
répondu 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('.'));

extension devrait avoir ".txt" lors de l'exécuter.

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

ici j'ai fait une petite méthode (cependant pas si sûr 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 généralement 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
répondu Rivalion 2015-06-15 21:53:52

obtenir une 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é 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
répondu Vasanth 2016-11-18 08:36:14

Que Diriez - vous de REGEX 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 une extension nulle supportée:

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: / root / docs/

nom: readme

Extension: txt

pour windows, parsePath("c:\windows\readme.txt"):

chemin: c:\windows\

nom: readme

Extension: txt

1
répondu Dmitry Sokolyuk 2017-03-28 10:49:13

sans utiliser de bibliothèque, vous pouvez utiliser la méthode de chaîne de caractères divisée comme suit:

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

        String extension = "";

        if(splits.length >= 2)
        {
            extension = splits[splits.length-1];
        }
1
répondu 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", faites path.lastIndexOf(".") + 1

1
répondu Clément Chameyrat 2017-08-24 15:57:32

Juste une expression régulière de remplacement. 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
répondu serhiy.h 2013-05-13 12:38:39

cette question particulière me pose beaucoup de problèmes puis j'ai trouvé une solution très simple pour ce problème que je poste ici.

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

C'est ça.

0
répondu vikram Bhardwaj 2016-04-24 08:11:29

j'ai trouvé une meilleure façon de trouver l'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
répondu 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
répondu 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
répondu Ashish Pancholi 2018-01-11 09:42:58

Java a une façon intégrée de traiter 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
répondu Nick Giampietro 2013-09-25 20:47:06