본문으로 바로가기
반응형

java io와 nio를 이용하여 어플리케이션을 만들다보면, 파일명, 디렉토리경로 등을 자유자재로 설정해야 할 때가 있습니다.
이럴 때 유용한, 파일명만 뽑아내는 예제입니다.

파일 경로에서 마지막 파일명만 뽑아내는 메서드를 만들고 싶으시다면, java.nio.file.Path와 java.nio.file.Paths 클래스를 사용하면 됩니다.

다음은 해당 메서드의 예시입니다:

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
public static void main(String[] args) {
String filePath = "/aa/bb/ccc/dddd/eee.20230518";
String fileName = getFileName(filePath);
System.out.println(fileName);
}

반응형

public static String getFileName(String filePath) {
Path path = Paths.get(filePath);
Path fileName = path.getFileName();
if (fileName != null) {
return fileName.toString();
} else {
return "";
}
}
}

이 코드는 입력된 파일 경로에서 마지막 파일명을 추출하고 출력합니다. Paths.get(filePath)로 파일의 경로를 표현하는 Path 객체를 생성하고, Path.getFileName() 메서드를 사용하여 파일 이름을 가져옵니다. 만약 getFileName() 메서드가 null을 반환하면, 입력된 경로가 파일 이름을 포함하지 않는 것으로 간주하여 빈 문자열을 반환합니다.

Random Photo

반응형