Programming

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

procodes 2020. 2. 16. 20:52
반응형

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


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

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

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


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

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

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

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

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

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

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

Android의 경우 다음을 사용할 수 있습니다.

String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());

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

String extension = "";

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

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

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

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

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

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

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


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

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

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

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

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

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

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에서 파일 확장자를 자르려면 어떻게해야합니까?


.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있도록 즉시 쓰레기 대신 힙의 스택에 넣어 .


Java 8을위한 또 하나의 라이너가 있습니다.

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

다음과 같이 작동합니다.

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

String path = "/Users/test/test.txt"

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

".txt"를 반환

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


// Modified from EboMike's answer

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

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


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

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

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


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

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

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

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

/**
 * 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

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

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

        String extension = "";

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

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

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

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

이 특정 질문은 나에게 많은 어려움을 주며 여기에 게시하는이 문제에 대한 매우 간단한 해결책을 찾았습니다.

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

그게 다야.


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

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

나는 스펙터의 대답 의 단순함을 좋아하고 그의 의견 중 하나에 링크 된 것은 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를 사용해야합니까?


이 시도.

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에는 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;

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

참고 URL : https://stackoverflow.com/questions/3571223/how-do-i-get-the-file-extension-of-a-file-in-java



반응형