Java에서 String에서 파일 확장자를 자르는 방법은 무엇입니까?
다음과 같이 Java에서 접미사를 트리밍하는 가장 효율적인 방법은 무엇입니까?
title part1.txt
title part2.html
=>
title part1
title part2
이것은 우리가 스스로 해서는 안 되는 종류의 코드입니다.평범한 일에는 도서관을 사용하고 딱딱한 일에는 머리를 아껴라.
이 경우 Apache Commons IO에서 FilenameUtils.removeExtension()을 사용할 것을 권장합니다.
str.substring(0, str.lastIndexOf('.'))
를 사용하는 경우String.substring
그리고.String.lastIndex
원라이너에서는 특정 파일 경로에 대처할 수 있는 몇 가지 문제가 있습니다.
예를 들어 다음 경로를 사용합니다.
a.b/c
원라이너를 사용하면 다음과 같은 결과가 초래됩니다.
a
틀렸습니다.
결과는 다음과 같았어야 했다.c
파일에는 확장자가 없지만 경로에는 확장자를 가진 디렉토리가 있습니다..
이름에서 원라이너 방식은 경로의 일부를 파일명으로 지정하도록 속여져 있는데, 이는 올바르지 않습니다.
체크의 필요성
Skaffman의 대답에 영감을 받아 Apache Commons IO의 방법을 살펴봤습니다.
동작을 재현하기 위해 새로운 메서드가 수행해야 할 테스트를 몇 가지 작성했습니다.다음은 그 예입니다.
경로 파일 이름-------------- --------a/b/c ca/b/c.jpg ca/b/c.jpg.jpg c.jpg a.b/c ca.b/c.jpg ca.b/c.jpg.jpg c.jpg c c cc.jpg cc.jpg.jpg c.jpg
(제가 체크한 것은 이것뿐입니다.아마도 제가 간과하고 있는 다른 체크가 있을 것입니다.)
실장소
이하에, 의 실장을 나타냅니다.removeExtension
방법:
public static String removeExtension(String s) {
String separator = System.getProperty("file.separator");
String filename;
// Remove the path upto the filename.
int lastSeparatorIndex = s.lastIndexOf(separator);
if (lastSeparatorIndex == -1) {
filename = s;
} else {
filename = s.substring(lastSeparatorIndex + 1);
}
// Remove the extension.
int extensionIndex = filename.lastIndexOf(".");
if (extensionIndex == -1)
return filename;
return filename.substring(0, extensionIndex);
}
실행 중removeExtension
위의 테스트를 사용한 방법은 위의 결과를 산출합니다.
이 메서드는 다음 코드를 사용하여 테스트되었습니다.Windows에서 실행되었기 때문에 경로 구분자는\
이것은, 로부터 탈출할 필요가 있습니다.\
의 일부로서 사용되었을 때String
문자 그대로의
System.out.println(removeExtension("a\\b\\c"));
System.out.println(removeExtension("a\\b\\c.jpg"));
System.out.println(removeExtension("a\\b\\c.jpg.jpg"));
System.out.println(removeExtension("a.b\\c"));
System.out.println(removeExtension("a.b\\c.jpg"));
System.out.println(removeExtension("a.b\\c.jpg.jpg"));
System.out.println(removeExtension("c"));
System.out.println(removeExtension("c.jpg"));
System.out.println(removeExtension("c.jpg.jpg"));
결과는 다음과 같습니다.
c
c
c.jpg
c
c
c.jpg
c
c
c.jpg
결과는 이 방법이 수행해야 하는 테스트에서 개략적으로 설명한 바람직한 결과입니다.
참고로 제 경우 특정 확장을 삭제하는 빠른 솔루션을 원했을 때 대략 다음과 같이 했습니다.
if (filename.endsWith(ext))
return filename.substring(0,filename.length() - ext.length());
else
return filename;
String foo = "title part1.txt";
foo = foo.substring(0, foo.lastIndexOf('.'));
당신은 매우 기본적인 이 기능을 시도할 수 있습니다.
public String getWithoutExtension(String fileFullPath){
return fileFullPath.substring(0, fileFullPath.lastIndexOf('.'));
}
String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
fileName=fileName.substring(0,dotIndex);
}
이거 속임수 질문인가요?:p
현금인출기보다 더 빠른 방법이 생각나지 않아요.
의 com.google.common.io.Files
: 가 이미 Google libraryclass(클래스)에 하고 있는 .한 방법은 요 you you you you you you you the you입니다.getNameWithoutExtension
하지만 마지막 결과 문구를 다음과 같이 변경했습니다.
if (extensionIndex == -1)
return s;
return s.substring(0, lastSeparatorIndex+1)
+ filename.substring(0, extensionIndex);
전체 경로 이름을 반환하고 싶었기 때문입니다.
즉, "C:\Users\mroh004"입니다.COM\문서\Test\Test.xml" 가 됩니다."C:\Users\mroh004.COM\문서\Test\Test"가 아닌"테스트"
filename.substring(filename.lastIndexOf('.'), filename.length()).toLowerCase();
정규식을 사용합니다.이게 마지막 점, 그리고 그 뒤의 모든 점을 대신하는 거야.
String baseName = fileName.replaceAll("\\.[^.]*$", "");
정규식을 미리 컴파일하려는 경우 패턴 개체를 만들 수도 있습니다.
Spring을 사용하면
org.springframework.util.StringUtils.stripFilenameExtension(String path)
지정된 Java 리소스 경로에서 파일 이름 확장자를 제거합니다.
"mypath/myfile.txt" -> "mypath/myfile" 입니다.
파라미터: 경로– 파일 경로
반환: 파일 이름 확장자가 제거된 경로
private String trimFileExtension(String fileName)
{
String[] splits = fileName.split( "\\." );
return StringUtils.remove( fileName, "." + splits[splits.length - 1] );
}
String[] splitted = fileName.split(".");
String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");
문자열 이미지 경로를 사용하여 새 파일 생성
String imagePath;
File test = new File(imagePath);
test.getName();
test.getPath();
getExtension(test.getName());
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
org.apache.commons.io 를 참조해 주세요.FilenameUtils 버전 2.4는 다음과 같은 답변을 제공합니다.
public static String removeExtension(String filename) {
if (filename == null) {
return null;
}
int index = indexOfExtension(filename);
if (index == -1) {
return filename;
} else {
return filename.substring(0, index);
}
}
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;
}
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);
}
public static final char EXTENSION_SEPARATOR = '.';
private static final char UNIX_SEPARATOR = '/';
private static final char WINDOWS_SEPARATOR = '\\';
Path 클래스를 고수하기 위해 쓸 수 있는 최선의 방법:
Path removeExtension(Path path) {
return path.resolveSibling(path.getFileName().toString().replaceFirst("\\.[^.]*$", ""));
}
나는 이렇게 하고 싶다.
String title_part = "title part1.txt";
int i;
for(i=title_part.length()-1 ; i>=0 && title_part.charAt(i)!='.' ; i--);
title_part = title_part.substring(0,i);
'.'까지 끝까지 이어서 서브스트링을 호출합니다.
편집: 골프는 아니지만 효과적입니다.
파일 확장자가 없거나 파일 확장자가 여러 개일 경우 유의하십시오.
예: 파일명 : file | file.txt | file.tar.bz2
/**
*
* @param fileName
* @return file extension
* example file.fastq.gz => fastq.gz
*/
private String extractFileExtension(String fileName) {
String type = "undefined";
if (FilenameUtils.indexOfExtension(fileName) != -1) {
String fileBaseName = FilenameUtils.getBaseName(fileName);
int indexOfExtension = -1;
while (fileBaseName.contains(".")) {
indexOfExtension = FilenameUtils.indexOfExtension(fileBaseName);
fileBaseName = FilenameUtils.getBaseName(fileBaseName);
}
type = fileName.substring(indexOfExtension + 1, fileName.length());
}
return type;
}
String img = "example.jpg";
// String imgLink = "http://www.example.com/example.jpg";
URI uri = null;
try {
uri = new URI(img);
String[] segments = uri.getPath().split("/");
System.out.println(segments[segments.length-1].split("\\.")[0]);
} catch (Exception e) {
e.printStackTrace();
}
그러면 img와 imgLink 양쪽의 예가 출력됩니다.
public static String removeExtension(String file) {
if(file != null && file.length() > 0) {
while(file.contains(".")) {
file = file.substring(0, file.lastIndexOf('.'));
}
}
return file;
}
private String trimFileName(String fileName)
{
String[] ext;
ext = fileName.split("\\.");
return fileName.replace(ext[ext.length - 1], "");
}
이 코드에 의해, 파일명이 「.」가 붙어 있는 부분(예: 「.」등).파일명이 file-name인 경우.그러면 hello.txt는 문자열 배열에 스필됩니다.{ file - name 」 、 「 hello 」 、 「 txt 」 。어쨌든 이 문자열 배열의 마지막 요소는 특정 파일의 파일 확장자가 되므로, 이 문자열 배열의 마지막 요소는 다음과 같이 됩니다.arrayname.length - 1
마지막 요소를 파악한 후 파일 확장자를 해당 파일 이름의 빈 문자열로 바꿀 수 있습니다.할 할 수 hello. 마지막 마침표도 삭제할 경우 반환행 문자열 배열의 마지막 요소에 마침표만 있는 문자열을 추가할 수 있습니다. 떻게게 which which which which which which which which which?
return fileName.replace("." + ext[ext.length - 1], "");
언급URL : https://stackoverflow.com/questions/941272/how-do-i-trim-a-file-extension-from-a-string-in-java
'itsource' 카테고리의 다른 글
String에 "를 추가하면 메모리가 절약되는 이유는 무엇입니까? (0) | 2022.07.21 |
---|---|
어떻게 하면 C 프리프로세서와 두 번 연결하여 "arg ##_# MACRO"처럼 매크로를 확장할 수 있습니까? (0) | 2022.07.21 |
Java에서 운영체제를 프로그래밍 방식으로 판별하려면 어떻게 해야 하나요? (0) | 2022.07.21 |
Vue.js - 개체를 다른 데이터 속성에 '복사'할 때 바인딩하지 않음 (0) | 2022.07.21 |
16진수를 C로 표시하는 방법 (0) | 2022.07.17 |