Mark W
Mark W

Reputation: 5964

write file contents to jsp

I would like to write the contents of a (text) file to a JSP. I will do this from within a tag What is the best way to grab the file contents and write to the object produced by a call to "pageContext.getOut()" from within my tag?

I ask as I am unsure of the various readers, writers and buffers etc.

Upvotes: 0

Views: 1540

Answers (4)

Thomas
Thomas

Reputation: 88757

If you don't want to use scriptlets you might create a functions class similar to the JSTL functions which provides a static method to do that. Then use an expression to read the file.

Example:

package your.pkg

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

In your taglib file you'd have this entry:

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

And finally in your 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

Upvotes: 1

Bohemian
Bohemian

Reputation: 425418

You could use the apache commons-io library. It has a utility method to get File contents as a String:

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

Caution - This convenient method is only for use with smallish files. If the file is large, a streaming approach is needed (where you write bytes to the output stream as you read them from the file)

Upvotes: 2

Qwerky
Qwerky

Reputation: 18455

You can just do a;

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

No readers/writers/buffers etc required.

Upvotes: 0

Ondra Žižka
Ondra Žižka

Reputation: 46904

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

And one of it's copy() methods.

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

Upvotes: 3

Related Questions