Java에서 확장자없이 파일 이름을 얻는 방법은 무엇입니까? 방법을 말해 줄 수 있습니까? 예: fileNameWithExt =

누구든지 확장자없이 파일 이름을 얻는 방법을 말해 줄 수 있습니까? 예:

fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";



답변

나처럼, 파일 이름이 아닌 경로 에 null 또는 점 을 전달하면 발생하는 것과 같은 모든 특수 사례를 생각한 라이브러리 코드 를 사용하려는 경우 다음을 사용할 수 있습니다.

import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);


답변

가장 쉬운 방법은 정규식을 사용하는 것입니다.

fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");

위의 표현은 마지막 점과 하나 이상의 문자를 제거합니다. 기본 단위 테스트는 다음과 같습니다.

public void testRegex() {
    assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
    assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}


답변

다음 테스트 프로그램을 참조하십시오.

public class javatemp {
    static String stripExtension (String str) {
        // Handle null case specially.

        if (str == null) return null;

        // Get position of last '.'.

        int pos = str.lastIndexOf(".");

        // If there wasn't any '.' just return the string as is.

        if (pos == -1) return str;

        // Otherwise return the string, up to the dot.

        return str.substring(0, pos);
    }

    public static void main(String[] args) {
        System.out.println ("test.xml   -> " + stripExtension ("test.xml"));
        System.out.println ("test.2.xml -> " + stripExtension ("test.2.xml"));
        System.out.println ("test       -> " + stripExtension ("test"));
        System.out.println ("test.      -> " + stripExtension ("test."));
    }
}

어떤 출력 :

test.xml   -> test
test.2.xml -> test.2
test       -> test
test.      -> test


답변

내 선호도에 따른 통합 목록 순서는 다음과 같습니다.

아파치 커먼즈 사용하기

import org.apache.commons.io.FilenameUtils;

String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);

                           OR

String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

Google Guava 사용 (이미 사용중인 경우)

import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);

또는 코어 자바 사용

1)

String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
    fileName = fileName.substring(0, pos);
}

2)

if (fileName.indexOf(".") > 0) {
   return fileName.substring(0, fileName.lastIndexOf("."));
} else {
   return fileName;
}

삼)

private static final Pattern ext = Pattern.compile("(?<=.)\\.[^.]+$");

public static String getFileNameWithoutExtension(File file) {
    return ext.matcher(file.getName()).replaceAll("");
}

Liferay API

import com.liferay.portal.kernel.util.FileUtil;
String fileName = FileUtil.stripExtension(file.getName());


답변

프로젝트에서 Guava (14.0 이상)를 사용하는 경우을 사용할 수 있습니다 Files.getNameWithoutExtension().

( 가장 높은 투표 응답에서 알 수 있듯이 FilenameUtils.removeExtension()Apache Commons IO 와 본질적으로 동일 합니다. 구아바도 마찬가지라고 지적하고 싶었습니다. 개인적으로 저는 Commons에 의존성을 추가하고 싶지 않았습니다. 이것 때문에.)


답변

아래는 https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java 에서 참조한 것입니다.

/**
 * Gets the base name, without extension, of given file name.
 * <p/>
 * e.g. getBaseName("file.txt") will return "file"
 *
 * @param fileName
 * @return the base name
 */
public static String getBaseName(String fileName) {
    int index = fileName.lastIndexOf('.');
    if (index == -1) {
        return fileName;
    } else {
        return fileName.substring(0, index);
    }
}


답변

전체 apache.commons를 가져 오지 않으려면 동일한 기능을 추출했습니다.

public class StringUtils {
    public static String getBaseName(String filename) {
        return removeExtension(getName(filename));
    }

    public static int indexOfLastSeparator(String filename) {
        if(filename == null) {
            return -1;
        } else {
            int lastUnixPos = filename.lastIndexOf(47);
            int lastWindowsPos = filename.lastIndexOf(92);
            return Math.max(lastUnixPos, lastWindowsPos);
        }
    }

    public static String getName(String filename) {
        if(filename == null) {
            return null;
        } else {
            int index = indexOfLastSeparator(filename);
            return filename.substring(index + 1);
        }
    }

    public static String removeExtension(String filename) {
        if(filename == null) {
            return null;
        } else {
            int index = indexOfExtension(filename);
            return index == -1?filename:filename.substring(0, index);
        }
    }

    public static int indexOfExtension(String filename) {
        if(filename == null) {
            return -1;
        } else {
            int extensionPos = filename.lastIndexOf(46);
            int lastSeparator = indexOfLastSeparator(filename);
            return lastSeparator > extensionPos?-1:extensionPos;
        }
    }
}