[개발] 자바

URL에서 파일이름만 가져오기

브랜든정 2011. 8. 31. 11:29
반응형

가끔씩 주어진 URL에서 파일이름만 가져와서 사용하고 싶은 경우 아래와 같은 함수를 적용하면 쉽게 가져올수 있다.


String path = "C:/test_folder/hello.txt";String fileName = new File(path).getName();

위 소스를 실행하면 아래와 같이 "hello.txt" 만 가져오게 된다.

 



URL에서 확장자 없이 파일이름만 가져오거나, 확장자만 가져오게 하려면 아래와 같이 약간의 수정이 필요하다.

public static String getFileNameWithoutExtension(String fileName) {
  File tmpFile = new File(fileName);        
  tmpFile.getName();        
  int whereDot = tmpFile.getName().lastIndexOf('.');        
  if (0 < whereDot && whereDot <= tmpFile.getName().length() - 2 ) {            
    return tmpFile.getName().substring(0, whereDot);     
    //extension = filename.substring(whereDot+1);        
  }            
  return "";
}
반응형