Java에서 파일의 파일 확장자를 얻으려면 어떻게합니까?


484

분명히하기 위해 MIME 유형을 찾고 있지 않습니다.

다음과 같은 입력이 있다고 가정 해 봅시다. /path/to/file/foo.txt

이 입력을 특히 .txt확장 을 위해 분리하는 방법을 원합니다 . Java로 이것을 수행하는 방법이 있습니까? 내 파서를 작성하지 않으려 고합니다.


12
확장 기능을 쉼표로 구분하여 정의하는 새로운 플랫폼이 언제 출시되는지 알 수 없습니다. 이제 플랫폼 종속 코드를 작성해야합니다. Java 프레임 워크는보다 진보적이어야하며 플랫폼 의존 코드를 작성하는 확장을 가져 오는 API를 가져야하며 API 사용자는 확장을 얻는다고 말합니다.
— ArtOfWarfare

@ArtOfWarfare : 세상에. 수천 개의 클래스로 100MB의 JRE를 만들어 보자 . 어딘가 일부 플랫폼에서 사용할 수 있기 때문에 반환 "txt"되는 메소드를 구현하지 "filename.txt"마십시오 "filename,txt".
— Eric Duminil

@EricDuminil ""filename.txt "에서"txt "를 반환하는 메소드를 구현하지 마십시오."??? 시도 path.substring(path.lastIndexOf("."));..... 그리고 그래 .. 그들은 아무것도 복제하지 않을 것입니다 ...
— VelocityPulse

@VelocityPulse 정확히 저를 귀찮게합니다. 파일 확장자를 얻는 표준 방법이 없으므로 수십 가지의 반답과 약간 다른 구현이 있습니다. 귀하의 코드는 2 개의 메소드 ( 하나의 명시 적 인 메소드를 원했습니다)를 사용합니다. ".txt"에서 반환 "filename.txt"합니다. 원하는 결과가 아닐 수도 있지만 최악의 StringIndexOutOfBoundsException경우 확장명이 없으면 빈 문자열을 반환하는 대신 실패 합니다.
— Eric Duminil

답변:


649

이 경우 Apache Commons IO의 FilenameUtils.getExtension 을 사용하십시오.

사용 방법의 예는 다음과 같습니다 (전체 경로 또는 파일 이름 만 지정할 수 있음).

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

메이븐 의존성 :

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

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


70
archive.tar.gz라는 파일에 대해서는 "gz"만 반환한다는 점에 유의하십시오.
— Zitrax

106
@Zitrax "gz"가 파일 확장자이기 때문입니다.
— BrainSlugs83

6
@ BrainSlugs83 "tar"은 무슨 뜻인가요?
— TuGordoBello

31
@zhelon .gz 는 gnu 압축 파일을 나타내고 .tar 는 (t) ape (ar) chive를 나타냅니다. 따라서 .tar.gz는 gzip 압축 파일의 tar 파일이며 확장자는 .gz입니다.
— cirovladimir

5
이 간단한 작업을 위해 다른 라이브러리를 가져올 이유가 없습니다.
— masterwok

311

정말로 "파서"가 필요합니까?

String extension = "";

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

단순한 Windows와 유사한 파일 이름을 다루고 있다고 가정합니다 archive.tar.gz.

Btw, 디렉토리에 '.'가있을 수 있지만 파일 이름 자체가 (예 :)이 아닌 경우 /path/to.a/file수행 할 수 있습니다

String extension = "";

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

if (i > p) {
    extension = fileName.substring(i+1);
}

4
감사! 물론 확장 기능보다 더 많은 조작을 원한다면 파서 / 객체가 필요할 수 있습니다 ... 경로, 부모 디렉토리, 파일 이름 (확장자 빼기) 등을 원한다면 말하십시오. m은 C #과 .Net에서오고 있습니다 : msdn.microsoft.com/en-us/library/…
— longda

10
당신이 말했듯이, 순진한 lastIndexOf ( ".")를 사용하는 것 외에도 고려해야 할 것이 많습니다. 나는 Apache Commons가 이것을위한 방법을 가지고 있다고 생각합니다.이 방법은 약간의 까다로운 잠재적 문제를 모두 고려합니다.
— MatrixFrog

12
또는 i > 0로 변경해야 한다고 생각 합니다 . 이 같은 파일 이름을 처리 합니다. i >= 0i != -1.htaccess
— Pijusn

8
코드 스 니펫이 얼마나 간단한 지에 관계없이 ... 여전히 업데이트 / 유지 관리 / 테스트 / 편리한 종속성으로 사용할 수 있도록해야합니다 ... 이미 모든 작업을 수행하는 lib가있는 경우 훨씬 쉽습니다.
— Don Cheadle

2
더 많은 문제는 파일이 점으로 끝나는 경우입니다. lib에서 더 좋습니다. if (i> p && i <(fileName.length ()-1)) {확장 = fileName.substring (i + 1);
— tgkprog

97
private String getFileExtension(File file) {
    String name = file.getName();
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf);
}

13
이것은 '.'을 반환한다는 점에 유의하십시오. 또한 다른 답변 중 일부는 'txt'가 아니라 '.txt'입니다.
— NickEntin

2
더 나은 답변과 @NickEntin 더 나은 의견. "."마침표를 제거하려면 파일 확장자에서 int lastIndexOf = name.lastIndexOf ( ".") + 1로 코딩 할 수 있습니다.
— Hanzallah Afgan

11
/usr/bin/foo.bar/httpconf
— Iman Akbari

8
@ lukasz1985 1. 수백 개의 리눅스 패키지가 "init.d"와 같은 이름을 가진 디렉토리를 만듭니다. 또한 불법이 ​​아니기 때문에 점이없는 디렉토리를 사용하는 경로에 의존하는 것은 안전하지 않습니다. 기억 나지 않지만 stackoverflow.com/a/3571239/2546146 에이 결함이없는 것 같습니다
— Iman Akbari

6
@Iman Akbari : getName ()은 파일 이름 자체 만 반환합니다 (이 예제에서는 "httpconf").
— Dreamspace President

85

Guava 라이브러리 를 사용하는 경우 Files유틸리티 클래스 를 이용할 수 있습니다 . 특정 방법이 getFileExtension()있습니다. 예를 들어 :

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

또한 비슷한 함수 getNameWithoutExtension ()을 사용하여 파일 이름을 얻을 수도 있습니다 .

String filename = Files.getNameWithoutExtension(path);
System.out.println(filename); //prints foo

4
정말? 유틸리티가 가득한 훌륭한 라이브러리입니다. 그들 대부분은 위대한 Guava Function 과 같은 Java8의 일부가 될 것입니다 .
— JeanValjean

불행히도 모든 사람들이 사용할 라이브러리를 결정할 수있는 것은 아닙니다. 적어도 아파치 커먼즈는 있지만 오래된 것이 긴하다.
— Lluis Martinez

1
getFileExtension실제로 소스 코드를 보면 int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1)그렇게 큰 문제 는 아닙니다. 또한 Files어떤 이유로 "불안정"으로 표시되어 있습니다.
— Al-Mothafar

@ Al-Mothafar 많은 클래스가 불안정한 것으로 표시되어 있습니다 (멀티 맵 빌더 참조). 또한 이유를 이해하지 못합니다. 여러 릴리스가 만들어졌지만 아무것도 변경되지 않았습니다.
— JeanValjean


14

점 앞에 문자가없는 파일 이름을 고려 하려면 허용 된 답변의 약간의 변형을 사용해야합니다.

String extension = "";

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

"file.doc" => "doc"
"file.doc.gz" => "gz"
".doc" => "doc"

아마도 "foo"로부터 스스로를 방어해야합니다. 입력.
— chrisinmtown

14

이것은 테스트 된 방법입니다

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();
}

그리고 테스트 사례 :

@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"));
}

10

String.replaceAll 사용하면 더럽고 가장 작을 수 있습니다 .

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

첫 번째 *는 욕심이 많기 때문에 가능한 한 대부분의 가능한 문자를 잡은 다음 마지막 점과 파일 확장자 만 남습니다.


파일의 확장자가 없으면 실패합니다.
— Zack

그러나 불행히도 여전히 빠른 파일 형식 감지와 같은 간단한 시나리오에 사용할 수 있으며 확장명이 잘못된 것과 전혀 다르지 않거나 대체 결과가 입력과 같을 때 if 조건을 지정할 수 있습니다.
— Ebrahim Byagowi

1
또는 더 짧은.replaceAll(".*\\.", "")
— Ebrahim Byagowi

10
String path = "/Users/test/test.txt";
String extension = "";

if (path.contains("."))
     extension = path.substring(path.lastIndexOf("."));

".txt"를 반환

"txt"만 원한다면 path.lastIndexOf(".") + 1


9

다른 모든 답변에서 알 수 있듯이 적절한 "내장"기능이 없습니다. 이것은 안전하고 간단한 방법입니다.

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;
}

7

어떻습니까 (Java 1.5 RegEx 사용) :

    String[] split = fullFileName.split("\\.");
    String ext = split[split.length - 1];

6

Apache commons-io를 사용하고 파일 확장자를 확인한 다음 일부 작업을 수행하려는 경우 이것을 사용할 수 있습니다 .

if(FilenameUtils.isExtension(file.getName(),"java")) {
    someoperation();
}

이 확인은 문서에 따라 대소 문자를 구분합니다.
— Babken Vardanyan 2016 년

6

다음은 Java 8을위한 또 하나의 라이너입니다.

String ext = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null)

다음과 같이 작동합니다.

  1. "."를 사용하여 문자열을 문자열 배열로 분할하십시오.
  2. 배열을 스트림으로 변환
  3. 스트림의 마지막 요소, 즉 파일 확장자를 얻으려면 reduce를 사용하십시오.

4

JFileChooser는 어떻습니까? 최종 출력을 구문 분석해야하므로 간단하지 않습니다 ...

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

이것은 MIME 유형입니다 ...

좋아 ... MIME 유형을 알고 싶지 않다는 것을 잊어 버렸습니다.

다음 링크의 흥미로운 코드 : 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;
}

관련 질문 : Java의 String에서 파일 확장자를 자르려면 어떻게해야합니까?


4

.tar.gz디렉토리 이름에 점이있는 경로에서도 올바르게 처리하는 방법은 다음과 같습니다 .

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);
}

afterLastSlashafterLastBackslash슬래시가 있으면 전체 문자열을 검색 할 필요가 없으므로 더 빨리 찾기 위해 작성됩니다 .

char[]원래 내부 String가 더 쓰레기를 추가하지, 재사용되고, JVM은 것입니다 아마 통지 그afterLastSlash 있도록 즉시 쓰레기 대신 힙의 스택에 넣어 .


이 방법은 구아바 소스 코드에서 복사 한 것입니다.
— 19:30에

1
나는 이것을 복사하지 않았다. 구아바 소스 코드에 있으면 여기에서 복사했습니다. 아마도 그들에게 알리십시오.
— Olathe

btw는 동일하지 않으므로 죄송합니다. 귀하와 Guava 개발자는 동일한 아이디어를 가질 수 있습니다.
— 19:42에

2
실제로 "gz"는 올바른 확장명입니다. 호출 코드가 "tar"도 처리 할 수 ​​있으면 getExtension함수 외부에서 추가로 확인해야 합니다. 사용자의 파일 이름 인 "my zip. don't touch.tar.gz"경우이 메소드는 잘못된 확장자를 리턴합니다.
— intrepidis

2
// Modified from EboMike's answer

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

확장자는 실행될 때 ".txt"가 있어야합니다.


13
이름에 확장자가 없으면 충돌이 발생합니다.
— EboMike

2

다음은 선택적 값을 반환 값으로 사용하는 버전입니다 (파일의 확장자가 있는지 확인할 수 없으므로).

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

REGEX 버전 은 어떻습니까?

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));
}

또는 null 확장명이 지원되는 경우 :

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);

* nix에 대한 결과 :
경로 : / root / docs /
이름 : readme
확장 : txt

Windows의 경우 parsePath ( "c : \ windows \ readme.txt") :
경로 : c : \ windows \
이름 : readme
확장 : txt


1
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");

1

여기에 작은 방법 (그러나 안전하지 않고 많은 오류를 확인하지는 않음)을 만들었지 만 일반적인 Java 프로그램을 프로그래밍하는 사람이라면 파일 유형을 찾기에 충분합니다. 복잡한 파일 형식에서는 작동하지 않지만 일반적으로 많이 사용되지는 않습니다.

    public static String getFileType(String path){
       String fileType = null;
       fileType = path.substring(path.indexOf('.',path.lastIndexOf('/'))+1).toUpperCase();
       return fileType;
}

OP는 내장 방법을 찾고 있습니다
— Panther

(1) lastIndexOf파일 이름 john.smith.report.doc이 올바르게 취급 되도록 사용해야합니다 . (2) 연장이없는 경우를 올바르게 처리해야합니다. 이 메소드는와 ABC/XYZ같은 경로를 반환 abc/xyz하지만 의미가 없습니다. ""또는 을 반환하는 것이 더 합리적 null입니다. (3) 파일 구분자가 항상 그런 것은 아닙니다 /.
— Radiodef

1

파일 이름에서 파일 확장자 얻기

/**
 * 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);
}

크레딧

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

라이브러리를 사용하지 않고 다음과 같이 String 메소드 split을 사용할 수 있습니다.

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

        String extension = "";

        if(splits.length >= 2)
        {
            extension = splits[splits.length-1];
        }

0

정규 표현식 기반의 대안 일뿐입니다. 그렇게 빠르지 않고 좋지 않습니다.

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

if (matcher.find()) {
    String ext = matcher.group(1);
}

0

위의 모든 답변을 혼합하여 확장 프로그램을 찾는 더 좋은 방법을 찾았습니다.

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

의 단순성과 같은 I 유령의 대답은 자신의 의견 중 하나에 연결하고, 또 다른 질문에 대한 파일 경로에서 수정 점이 다른 답변에 대한 링크입니다 EboMike에 의해 입니다.

어떤 종류의 타사 API를 구현하지 않으면 다음과 같이 제안합니다.

private String getFileExtension(File file) {

    String name = file.getName().substring(Math.max(file.getName().lastIndexOf('/'),
            file.getName().lastIndexOf('\\')) < 0 ? 0 : Math.max(file.getName().lastIndexOf('/'),
            file.getName().lastIndexOf('\\')));
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf + 1); // doesn't return "." with extension
}

이와 같은 것이 파일 형식을 전달 해야하는 ImageIO의 모든 write메소드 에서 유용 할 수 있습니다 .

DIY를 할 때 왜 전체 타사 API를 사용합니까?


0

이 특정 질문은 나에게 많은 문제를 안겨 주었고 여기에 게시하는이 문제에 대한 매우 간단한 해결책을 찾았습니다.

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

그게 다야.


3
OP 확장을 추출하는 방법이 필요합니다. 확장을 테스트하지 마십시오.
— Predrag Manojlovic

실제로 대부분의 경우에 개발중인 모든 것은 특정 유형의 파일 만 처리해야합니다 .. 문제 가이 영역에 오면 도움이 될 것입니다.
— Vikram Bhardwaj

4
그의 요구 사항을 다루지 않는
— Predrag Manojlovic

2
이것은 질문에 대한 답변이 아니지만 실제로 내가 찾던 것이 었습니다.
— Ediolot

-1

이 시도.

String[] extension = "adadad.adad.adnandad.jpg".split("\\.(?=[^\\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg

-1
  @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());
    }

-4

Java에는 java.nio.file.Files 클래스 에서이를 처리하는 기본 제공 방법이 있습니다.

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

이 정적 메소드는 여기 에 있는 스펙을 사용하여 "콘텐츠 유형"을 검색 할 수 있습니다.


28
이것은 올바르지 않습니다. probeContentType의 리턴 유형은 파일 확장자가 아닌 Mime 컨텐츠 유형입니다. 일반적으로 확장명과 일치하지 않습니다. 실제로 파일 형식을 확인하기 위해 파일을 열기 때문에 파일 브라우저에서도 속도가 느려집니다.
— Charles
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.