웹 개발

java] file path에서 파일명만 가져오는 방법

노루아부지 2021. 5. 2. 14:33

프로그래밍을 하다 보면 아래와 같이 파일 경로에서 파일명만 추출해야 하는 경우가 생각보다 많습니다.

예를 들어 C:/Document/Temp/FileName.txt 에서 FileName.txt만 추출해야 할 경우 입니다.

 

방법 1. File.getName() 사용

java.io.File 클래스의 getName() 메서드를 이용한 방법이 있습니다.

import java.io.File;

public class Test {
  public static void main(String [] args) {
    File f = new File("C:\\Document\\Temp\\FileName.txt");
    System.out.println(f.getName());
  }
}

 

 

방법 2. Path(java 7+) 를 사용

java.nio.file.Path의 getFileName() 메서드를 이용한 방법이 있습니다.

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

public class Test {
  public static void main(String [] args) {
    Path f = Paths.get("C:\\Document\\Temp\\FileName.txt");
    System.out.println(f.getFileName().toString());
  }
}

 

방법 3. Apache Commons IO의 FilenameUtils를 사용

*maven, gradle 및 jar 파일 다운로드

import org.apache.commons.io.FilenameUtils;

public class Test {
  public static void main(String [] args) {
    String name = FilenameUtils.getName("C:\\Document\\Temp\\FileName.txt");
    System.out.println(name);
  }
}

 

 

방법 4. lastIndexOf, substring 사용

public class Test {
  public static void main(String [] args) {
    String fullPath = "C:\\Document\\Temp\\FileName.txt";
    int index = fullPath.lastIndexOf("\\");
    String fileName = fullPath.substring(index + 1);
		
    System.out.println(fileName);
  }
}

 

 

 

참고 사이트

stackoverflow.com/questions/14526260/how-do-i-get-the-file-name-from-a-string-containing-the-absolute-file-path

 

728x90
loading