【问题标题】:write file contents to jsp将文件内容写入jsp
【发布时间】:2011-07-22 13:58:50
【问题描述】:

我想将(文本)文件的内容写入 JSP。我将在标签内执行此操作 从我的标签中获取文件内容并写入通过调用“pageContext.getOut()”生成的对象的最佳方法是什么?

我问是因为我不确定各种读取器、写入器和缓冲区等。

【问题讨论】:

    标签: java file jsp jsp-tags


    【解决方案1】:

    试试 Commons-IO:http://commons.apache.org/io/api-release/index.html?org/apache/commons/io/package-summary.html

    其中之一是copy() 方法。

    IOUtils.copy( 
       new FileInputStream( new File(...) ), 
       pageContext.getResponse().getOutputStream() 
    );
    

    【讨论】:

      【解决方案2】:

      您可以使用apache commons-io library。它有一个实用方法来获取文件内容作为字符串:

      String contents = FileUtils.readFileToString(new File("somefile.txt"));
      

      注意 - 这种方便的方法仅适用于较小的文件。如果文件很大,则需要 流式处理 方法(在从文件中读取字节时将字节写入输出流)

      【讨论】:

      • 如果文件很大,那就是真的 - 我已经编辑了答案以添加警告说明。 +1 好评论。
      【解决方案3】:

      如果您不想使用 scriptlet,您可以创建一个类似于 JSTL 函数的函数类,它提供了一个静态方法来执行此操作。然后使用表达式读取文件。

      例子:

      package your.pkg
      
      public class FileAccess {
        public static String readTxtFile( String filename )  {
           return FileUtils.readFileToString(new File(filename)); //used Bohemian's suggestion here :)
        }
      }
      

      在你的 taglib 文件中你会有这个条目:

      <function>
        <name>readTxtFile</name>
        <function-class>
          your.pkg.FileAccess 
        </function-class>
        <function-signature>
          java.lang.String readTxtFile( java.lang.String )
        </function-signature>
      </function>
      

      最后在你的 JSP 中:

      <%@taglib prefix="f" uri="your taglib uri" %>
      
      ${f:readTxtFile( 'path/to/myfile.txt' )} //reads the file and writes the return value to the JSP
      

      【讨论】:

        【解决方案4】:

        你可以做一个;

        <jsp:include page="myfile.txt">
        

        不需要读取器/写入器/缓冲区等。

        【讨论】:

        • 只有当文件位于同一个 Web 项目/WEB-INF 中时才有效,不是吗?
        • 托马斯,你是对的。由于该文件不在项目中。此选项不可行
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-28
        • 2012-05-18
        • 1970-01-01
        • 2013-08-01
        • 2010-11-09
        • 2018-01-08
        • 1970-01-01
        相关资源
        最近更新 更多