2013-05-24 2 views
1

나머지를 사용하여 .xml 문서에서 파일을 만들 수 있음을 보여주고 있습니다. 이것은 아래 코드입니다. 내가 그것을 실행할 때마다 "작동하지 않음"이 반환되어 파일이 존재하지 않는다는 것을 의미합니다. articles.xml 파일이 내 WEB-INF 폴더에 있고,이 작업을 수행하는 방법을 알 수 없습니다. 이 파일 경로에 대한 잘못된 레이아웃입니까? xml을 이와 같은 파일로 변환 할 수 있습니까?xml 파일을 이클립스에서 파일 형식으로 변환하는 방법

@Path("test") 
@GET 
@Produces(MediaType.TEXT_PLAIN) 
public String test() 
{ 
    try 
      { 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     } 
    catch (ParserConfigurationException e) 
      { 
     return "caught"; 
    } 

     File file = new File("/WEB-INF/Articles.xml"); 
     if (file.exists()) 
      return "its working"; 
     else 
      return "not working"; 


} 
+0

"/"는 절대 경로를 의미하므로 작업 디렉토리와 관련된 경로를 사용하려면 제거하십시오. 또한 절대 파일 경로를 반환하여'file.getCanonicalPath()'를 사용하여 현재 진행중인 작업을 검사하여 전체 파일 경로를 볼 수 있습니다 – Jacopofar

답변

0

WAR 리소스를로드하는 표준 방법은 ServletContext입니다. 이 코드는 Context 주석을 사용하여 삽입 할 수 있습니다.

@Context 
    private ServletContext context; 
    private Document articles; 

    @PostConstruct 
    public void init() { 
    try { 
     InputStream in = context.getResourceAsStream("/WEB-INF/Articles.xml"); 
     try { 
     articles = DocumentBuilderFactory.newInstance() 
             .newDocumentBuilder() 
             .parse(in); 
     } finally { 
     in.close(); 
     } 
    } catch (Exception e) { /*TODO: better handling*/ 
     throw new IllegalStateException(e); 
    } 
    } 

    @Path("test") 
    @GET 
    @Produces(MediaType.TEXT_PLAIN) 
    public String test() { 
    return articles == null ? "not working" : "its working"; 
    } 

글래스 피쉬 3.1.1에서 테스트되었습니다.

관련 문제