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.
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"
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);
}
private String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}
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
si sur Android, vous pouvez utiliser ceci:
String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());
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"
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.
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"));
}
(à l'aide de Java 1.5 (RegEx):
String[] split = fullFileName.split("\.");
String ext = split[split.length - 1];
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();
}
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;
}
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?
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 .
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();
}
}
}
// 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.
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");
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;
}
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
- 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
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
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];
}
path = "/Users/test/test.txt"
extension = path.substring(path.lastIndexOf("."), path.length());
retour ".txt "
si vous voulez seulement "txt", faites path.lastIndexOf(".") + 1
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);
}
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.
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));
}
essayez ceci.
String[] extension = "adadad.adad.adnandad.jpg".split("\.(?=[^\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg
@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());
}
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.