views:

16

answers:

1

I transfer a (*.txt)'s path by request.setAttribute("path", textpath); in servlet.java to a *.jsp. And the *.txt is in webserver address.How to show the content to textArea?Thank you.

A: 

Since you're talking JSP and reading files, I infer we're talking Java. You want to read the contents of a file into a string, right?

Here's a Java method for doing that.

/**
 * 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);
}

So you would call this like String fileContents = getFileContents(textPath);.

Then, in your page, you would say, <textarea><%= fileContents %></textarea>.

sidewaysmilk