2010-05-20 3 views
1

다시 나입니다.) 또 다른 문제가 있습니다. 웹에서 파일 (예 : -xtxt)을로드하고 싶습니다. 내 관리 빈의 다음 코드를 사용하려고 :인터넷에서 내 jsf 앱으로 txt 파일을로드하려면 어떻게해야합니까?

public void run() 
{ 
    try 
    { 
    URL url = new URL(this.filename); 
    URLConnection connection = url.openConnection(); 
    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    if (bufferedReader == null) 
    { 
    return; 
    } 

    String str = bufferedReader.readLine(); 
    while (bufferedReader.readLine() != null) 
    { 
    System.out.println("---- " + bufferedReader.readLine()); 
    } 
} 
    catch(MalformedURLException mue) 
    { 
    System.out.println("MalformedURLException in run() method"); 
    mue.printStackTrace(); 
    } 
    catch(IOException ioe) 
    { 
    System.out.println("IOException in run() method"); 
    ioe.printStackTrace(); 
    } 
    finally 
    { 
    try 
    { 
     bufferedReader.close(); 
    } 
    catch(IOException ioe) 
    { 
     System.out.println("UOException wile closing BufferedReader"); 
     ioe.printStackTrace(); 
    } 
    } 
} 


    public String doFileUpdate() 
    { 
    String str = FacesContext.getCurrentInstance().getExternalContext().getRequestServletPath(); 
    System.out.println("111111111111111111111 str = " + str); 
    str = "http://narod.ru/disk/20957166000/test.txt.html";//"http://localhost:8080/sfront/files/test.html"; 
    System.out.println("222222222222222222222 str = " + str); 
    FileUpdater fileUpdater = new FileUpdater(str); 
    fileUpdater.run(); 

    return null; 
    } 

그러나 BufferedReader로 내가 관리 빈의 메소드를 호출하는 것을 시도하고 현재 페이지의 HTML 코드를 반환합니다. 그것은 매우 이상한 일입니다. 저는 봤는데 아무도이 문제가 없었습니다.

어쩌면 내가 뭔가 잘못했는지, 아마도 net API를 사용하지 않는 웹 (jsf) 앱에 파일을로드하는 가장 간단한 방법이있을 수 있습니다. 어떤 아이디어?

도움 주셔서 대단히 감사드립니다.

업데이트 :

어쩌면 일부 JSF 코드가 도움이 될 것입니다 :

 <ui:composition xmlns="http://www.w3.org/1999/xhtml" 
       xmlns:ui="http://java.sun.com/jsf/facelets" 
       xmlns:a4j="http://richfaces.org/a4j" 
       xmlns:rich="http://richfaces.org/rich" 
       xmlns:h="http://java.sun.com/jsf/html" 
       xmlns:f="http://java.sun.com/jsf/core" 
       xmlns:fc="http://www.fusioncharts.com" 
       xmlns:t="http://myfaces.apache.org/tomahawk" 
       template="template.xhtml"> 
     <ui:define name="title">Add company page</ui:define> 
     <ui:define name="content"> 
     <h:form id="addCompanyForm"> 
      <h:outputText value="Add a new company"/><br/><br/><br/> 
      <div style="width: 400px;"> 
       <table width="100%" cellpadding="0" cellspacing="0"> 
        <tr> 
         <td width="1"> 
          Company name: 
         </td> 
         <td> 
          <h:inputText id="companyName" value="#{companyBean.companyName}" style="width: 100%;" required="true" /> 
         </td> 
        </tr> 
        <tr> 
         <td valign="top" nowrap="nowrap"> 
          Company description:&#160; 
         </td> 
         <td> 
          <h:inputTextarea value="#{companyBean.companyDescription}" style="width: 100%;"/> 
         </td> 
        </tr> 
       </table><br/> 
       <center> 
        <h:commandButton value="Save company" action="#{companyBean.doInsertCompany}" style="width: 40%;"/>&#160;&#160; 
        <a4j:commandButton ajaxSingle="true" value="Clear" actionListener="#{companyBean.doClear}" style="width: 40%;" reRender="addCompanyForm"/> 
       </center> 
       <br/><br/><br/> 

       <h:commandLink value="Return to companies page" action="companies" immediate="true" /> 

      </div> 
     </h:form> 

     <h:form> 
      <br/> 
      <h:commandButton value="File Update" action="#{companyBean.doFileUpdate}" style="width: 10%;"/>&#160;&#160; 
     </h:form> 
    </ui:define> 
</ui:composition> 

업데이트 2 : 나는 (로컬 호스트되지 않음) 웹에서 다른 파일을 - 모든 것이 잘 작동! 이것에 대해 미안하다))))

BalusC가 말했듯이, 내 앱은 단지 URL : http://localhost:8080/sfront/files/test.txt로 파일을 찾지 못했습니다.

로컬 파일을 사용할 수없는 이유를 알지 못합니다.

아이디어가 있으십니까?

+0

당신은 몇 가지 코드를 형식화하는 필요 ... – mosg

+0

나는 몇 가지 코드를 포맷. @ 엘레나 : 메시지를 편집하는 동안 오른쪽 열의 서식 규칙에주의를 기울여야하며 페이지 하단의 미리보기 섹션을 사용하여 모든 것이 잘 보이는지 확인하십시오. – BalusC

+0

도와 주셔서 감사합니다.))) 어떤 코드를 만들었습니까? 내 브라우저 (Opera 10.53)에서는 모든 것이 잘 보입니다. 소스 코드의 경우 4 칸 (더 많은)을 수행합니다.당신은 나에게 무엇을 잘못 말했고 어떻게 해결할 수 있습니까? – Elena

답변

1

이것을 실제로 JSF 페이지에 포함하려면 JSTLc:import을 사용하는 것이 좋습니다.

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
... 
<c:import url="http://narod.ru/disk/20957166000/test.txt.html" /> 

훨씬 쉽습니다. 그러나 이것은 JSP에서 JSF를 사용하는 경우에만 작동합니다. Facelets의 JSF에서는 작동하지 않으며 불행히도 simliar 기능을 제공하지 않습니다.

실제 문제 : 설명 된 문제가 멀리 게시 된 코드 정보의 범위를 벗어나거나 실행중인 코드를 실행하지 않았기 때문에 잘 모르겠다. (웹 서버를 다시 시작하여 Java 코드의 최신 변경 사항이 컴파일 됨). 적어도 this.filename은 잘못된 값을 반환했으며 사용자가 자신의 웹 페이지 URL에 대해 주석을 달았 음을 알았습니다. 어쩌면 이것을 변경했지만 테스트하기 전에 hotdeploy가 실패했거나 서버가 다시 시작되지 않았을 수 있습니다.

더보기 당신은 BufferedReader에서 모든 두 번째 줄만 인쇄하고 모든 첫 번째 줄을 무시한다는 것을 알았습니다.

while (bufferedReader.readLine() != null) // You're ignoring first line. 
{ 
    System.out.println("---- " + bufferedReader.readLine()); // You're only printing next line. 

이것은 작동하지 않습니다. 당신은 하나의 큰 String에서 파일을 원하는 가정, 당신은 제대로 BufferedReader#readLine()를 사용하려면 다음 관용구를 따라야합니다

BufferedReader reader = null; 
StringBuider builder = new StringBuilder(); 
try { 
    reader = new BufferedReader(new InputStreamReader(someInputStream, "UTF-8")); 
    for (String line = null; (line = reader.readLine()) != null;) { 
     builder.append(line).append("\n"); // Append newline as well since readLine() eats them. 
    } 
} finally { 
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {} 
} 
String content = builder.toString(); 
+0

안녕하세요, BalusC! 빠른 답변 주셔서 감사합니다! 몇 분 후에 귀하의 제안을 시도하겠습니다. 이제 내가 필요한 것을 설명하려고 노력할 것입니다 - 매개 변수로 일부 파일 (txt 파일, xls, sql 일 수 있음)의 URL을 수신 할 방법이 필요하며 해당 파일과 프로세스의 정보를 읽으려고합니다 나중에. 그 파일의 정보 대신 현재 페이지의 소스 코드를받습니다. – Elena

+0

예, 이미 이해했습니다. 이것은 단지 URL이 잘못되었음을 나타냅니다. 'this.filename'의 값을 확인하십시오. 또는 서버를 다시 시작하십시오. – BalusC