2010-08-11 18 views
0

我將servlet.java中的request.setAttribute("path", textpath);的(* .txt)路徑傳送給* .jsp。並且* .txt在web服務器地址中。如何將內容顯示到textArea?謝謝。如何將文本顯示到* .jsp中的textArea?

+0

這是什麼? Java或JavaScript? – leppie 2010-08-11 16:54:38

+0

除了@ leppie的問題,textPath是服務器或客戶端上文件的路徑嗎? – Mark 2010-08-11 16:56:25

回答

0

既然你在談論JSP和閱讀文件,我推斷我們正在談論Java。你想將文件的內容讀入字符串中,對嗎?

這是一個Java方法。

/** 
* Return the contents of file as a String. 
* 
* @param file 
*   The path to the file to be read 
* @return The contents of file as a String, or null if the file couldn't be 
*   read. 
*/ 
private static String getFileContents(String file) { 

    /* 
    * Yes. This really is the simplest way I could find to do this in Java. 
    */ 

    byte[] bytes; 
    FileInputStream stream; 
    try { 
    stream = new FileInputStream(file); 
    } catch (FileNotFoundException e) { 
    System.out.println("File not found: `" + file + "`"); 
    e.printStackTrace(); 
    return null; 
    } 
    try { 
    bytes = new byte[stream.available()]; 
    stream.read(bytes); 
    stream.close(); 
    } catch (IOException e) { 
    System.out.println("IO Exception while getting contents of `" 
     + file + "`"); 
    e.printStackTrace(); 
    return null; 
    } 
    return new String(bytes); 
} 

所以你可以這樣稱呼它,就像String fileContents = getFileContents(textPath);

然後,在您的頁面上,您會說,<textarea><%= fileContents %></textarea>

相關問題