2011-08-04 2 views
2

Eclipse에서 동적 웹 프로젝트를 만들고 속성 파일에서 읽을 수있는 간단한 코드를 작성했습니다. 나는 예외를 파일을 찾을 수 없습니다있어이 작업을 실행하면
여기에 내 코드속성 파일에서 값 읽기

public class AutocompleteService { 

public static void main (String args[]) 
{ 
    Properties properties = new Properties(); 
    properties.load(new FileInputStream("autocomplete.properties")); 
    System.out.println("Test : " + properties.getProperty("test")); 
} 

입니다.

java.io.FileNotFoundException: autocomplete.properties (The system cannot find the file specified) 

내 패키지 구조는

-src 
- com.serive (package) 
    - AutocompleteService.java 
    - autocomplete.properties 

AutocompleteService.java 다음과 같이하고 autocomplete.properties 우리가 파일 속성에서 읽기 위해 아무것도 할 필요가 즉 com.service 수도 있었죠 동일한 패키지에?

참조 : http://www.exampledepot.com/egs/java.util/Props.html

~ Ajinkya. 당신이 스트림이있을 때

ClassLoader loader = Thread.currentThread().getContextClassLoader(); 
stream = loader.getResourceAsStream(fileName); 

당신이) (귀하의 코드는 "현재 디렉토리"에 찾고

답변

5

는 클래스에 스트림 상대를 가져옵니다 :

AutocompleteService.class.getResourceAsStream("autocomplete.properties") 
+0

고마워요 :) 그것은 효과적이고 다른 사람들보다 덜 복잡합니다.:) – xyz

+0

은'getResourceAsStream'이어야합니다. – Thilo

+0

@Thilo : 그래야합니다 .' properties.load (AutocompleteService.class.getResourceAsStream ("autocomplete.properties")); ' – xyz

7

당신은 클래스 패스에서이 문제를로드 할 수 응용 프로그램이 실행될 때

Class.getResourceAsStream()을 사용하면 클래스와 동일한 위치에서 읽을 수 있습니다.

2

을 Properties.load로에 전달할 수있는 예 :

+0

그래서'com.service'는 현재 현재 디렉토리가 아닙니까? – xyz

+0

아니요, 응용 프로그램을 시작하는 방법에 따라 다릅니다. 일반적으로 Eclipse에서 작업 할 때 작업 영역 디렉토리가됩니다. 구성 실행, 인수 탭에서이를 제어 할 수 있습니다. 하지만 응용 프로그램을 독립 실행 형으로 실행하면 응용 프로그램이 JAR에있을 수 있으므로 클래스 디렉토리가 현재 디렉토리가 될 것이라고 기대할 수 없습니다. getResourceAsStream()을 사용하면 Eclipse 및 독립 실행 형에서 작업 할 수 있습니다. – djna

0

가 실행중인 프로그램의 현재 디렉토리에있는 파일을 열려고 시도하는 상대 경로를 사용하여 입력 스트림을 생성. 귀하의 경우 현재 디렉토리는 서블릿 컨테이너 (Tomcat, Jetty 등)의 실행 디렉토리입니다.

당신이 원하는 것은 당신의 클래스와 함께 위치하고있는 속성 파일을 열 때입니다 파일. 따라서이 특성 파일은 클래스 로더에 의해 해석되어야하며 적절한 방법은 Class.getResourceAsStream()을 사용하는 것입니다. 링크 된 javadoc을보고 인수로 제공 할 경로의 종류를 파악하십시오.

2

"현재"디렉토리는 서버를 시작한 곳이므로 파일과 관련하여이를 참조하십시오 (예 : "config/autocomplete.properties" 또는 원하는 곳).

가장 좋은 방법은 을 알고을 아는 것입니다. 문제를 디버깅하는 데 도움이 같은 코드를 사용 :이 폭발하는 경우는 파일이 생각하고, 신속하게 문제를 해결하는 방법을 알아낼 yo'll 곳

File propertiesFile = new File("config/autocomplete.properties"); 
if (!propertiesFile.exists()) 
    throw new IllegalStateException("Could not find properties file: " + propertiesFile.getAbsolutePath()); 
properties.load(new FileInputStream(file)); 

는 예외 메시지가 표시됩니다.