2015-02-02 3 views
0

java가 실행중인 jar와 같은 폴더에서 .properties 파일을 찾길 원합니다. 나는 그것을 할 수 있으며 응용 프로그램은 IDE 또는 명시 적 jar 파일에서 실행중인 경우 어떻게 내가 확인하는 방법을런타임에서 jar 경로를 얻는 방법

을 통해 (이 클래스 경로에있는 경우)이 파일을 액세스 할 수 있습니다
+0

위대한 방법은 아닙니다.1) jar 파일에 속성을 넣거나 2) 현재 작업 디렉토리에 상대적인 어딘가에 속성을 두거나 (jar를 시작하기 전에 cwd를 변경하는 등) 또는 3) 잘 알려진 (하드 코드 된 또는 환경별로 구성 가능) 위치 (think /etc/myapp/config.props) – Thilo

+0

하지만해야 할 일 : http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running- jar-file? rq = 1 – Thilo

+0

방법이 있습니다. 오히려 hackish입니다. 몇 분만 기다려주세요. 내 파일에서 찾아서 대답을 게시 할 것입니다. –

답변

0

: 첫째로 내가 가진

Paths.get(this.getClass().getResource("file.properties").toURI()); 
+1

아마 classpath에 없습니다. – Thilo

0

인생은 종종 완벽하지 않고 때로는 나쁜 디자인 펀치로 굴러 가야하지만 이것은 본질적으로 나쁜 습관이라고 말할 수 있습니다.

public class ArbitraryPath { 

    private static Logger logger = LogManager.getLogger("utility"); 

    private static boolean isRunFromJar = false; 

    public static String resolveResourceFilePath(String fileName, String folderName, Class<?> requestingClass) throws URISyntaxException{ 
     // ARGUMENT NULL CHECK SAFETY HERE 
     String fullPath = requestingClass.getResource("").toURI().toString(); 
     isRunFromJar = isRunFromJar(fullPath); 
     String result = ""; 

     if(!isRunFromJar){ 
      result = trimPathDownToProject(requestingClass.getResource("").toURI()); 
     } 
     result = result+folderName+"/"+fileName+".properties"; 

     return result; 
    } 

    private static String trimPathDownToProject(URI previousPath){ 
     String result = null; 

     while(!isClassFolderReached(previousPath)){ 
      previousPath = previousPath.resolve(".."); 
     } 
     previousPath = previousPath.resolve(".."); 
     result = previousPath.getPath(); 
     return result; 
    } 

    private static boolean isClassFolderReached(URI currentPath){ 
     String checkableString = currentPath.toString(); 
     checkableString = checkableString.substring(0,checkableString.length()-1); 
     checkableString = checkableString.substring(checkableString.lastIndexOf("/")+1,checkableString.length()); 
     if(checkableString.equalsIgnoreCase("bin")){ 
      return true; 
     } else { 
      return false; 
     } 
    } 

    private static boolean isRunFromJar(String fullPath) throws URISyntaxException{ 
     String solidClassFolder = "/bin/"; 
     String solidJarContainer = ".jar!"; 
     if(!fullPath.contains(solidClassFolder)){ 
      if(fullPath.contains(solidJarContainer)){ 
       return true; 
      } else { 
       logger.error("Requesting class is not located within a supported project structure!"); 
       throw new IllegalArgumentException("Requesting class must be within a bin folder!"); 
      } 
     } else { 
      return false; 
     } 
    } 

} 

내가 설명 조금 추측 위해 ... 전체

이 해결하려고합니다 :

이 이러한 기능을 필요 나는 내 애완 동물 프로젝트를 위해 소집 클래스입니다 임의의 프로젝트에있는 특성 파일의 파일 경로. 즉, ArbitraryPath 클래스는 속성 파일과 동일한 프로젝트에 있어야 할 필요가 없습니다. 예를 들어 별도의 프로젝트에서 JUnit 테스트를 분리하려는 경우 유용합니다. 클래스를 기반으로 프로젝트를 식별합니다. 클래스는 찾으려고하는 속성 파일과 동일한 프로젝트에 있어야합니다.

String fullPath = requestingClass.getResource("").toURI().toString(); 

그 다음이 클래스는 JAR 파일 내에 있는지 여부를 확인하거나이 IDE에서 실행되는 경우 :

은 모든 그래서 일단 당신이이 줄을 준 클래스의 경로를 가져옵니다 . 이것은 경로에 "/ bin /"이 들어 있는지 검사하여 수행됩니다. 보통 "/ bin /"은 IDE 또는 ".jar!" 이는 보통 JAR에서 실행된다는 것을 의미합니다. 프로젝트 구조가 다른 경우 메서드를 수정할 수 있습니다.

NOT이 JAR에서 실행되는 것으로 확인되면 프로젝트 폴더까지 경로를 트리밍하고 BIN 폴더에 도달 할 때까지 경로를 거꾸로 이동합니다. 프로젝트 구조가 표준을 벗어나는 경우 다시 변경하십시오.

그 후

을 (우리가 이 JAR 파일에서 실행 우리가 이미 기본 폴더의 경로를 가지고 있기 때문에 우리는 아무것도 트림하지 않는가. IS하다고 판단되면) 우리가 경로를 검색 한 을 프로젝트 폴더에 추가하여 속성 파일이있는 폴더의 이름 (있는 경우)을 추가하고 찾을 속성 파일의 파일 이름과 확장명을 추가합니다.

그런 다음이 경로를 반환합니다. 우리는 다음과 같은 같은의 InputStream이 경로를 사용할 수 있습니다 :

FileInputStream in = new FileInputStream(ArbitraryPath.resolveResourceFilePath("myPropertiesFile", "configFolder", UserConfiguration.class)); 

어떤 UserConfiguration.class가있는 프로젝트 폴더에 myConfiguration 폴더에 myPropertiesFile.properties를 검색합니다.

이 클래스는 표준 프로젝트 구성이 있다고 가정합니다. 필요에 따라 자유롭게 적용하십시오.

또한이 작업을 수행하는 데 실제로 익숙하지 않은 방법입니다.

-1
String absolutePath = null; 
try { 
    absolutePath = (new File(Utils.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())).getCanonicalPath(); 
    absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator))+File.separator; 
} catch (URISyntaxException ex) { 
    Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); 
} catch (IOException ex) { 
    Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); 
} 
관련 문제