简体   繁体   中英

Reading a file in Servlet program

I am trying to understand what is the correct way to read a file in Java Servlet program. I need to read a file from a fixed path on my machine using my servlet code. Now I can read the file in multiple ways and one of the way which I am planning to use is to read the information in bytes as shown in below code:

private static void readFile(HttpServletRequest req, HttpServletResponse resp, String path)
    throws IOException
  {
    File file = new File("C:\\temp\", path);

    if (!file.isFile()) {
      resp.sendError(404, "File not found: " + file);
      return;
    }
    InputStream in = null;
    ServletOutputStream out = null;
    try {
      resp.setContentLength(Long.valueOf(file.length()).intValue());
      resp.resetBuffer();
      out = resp.getOutputStream();
      in = new BufferedInputStream(new FileInputStream(file));
      readFile(in, out);
    }
    finally {
     //Code for closing the input & output steams
      }
    }
  }

 public static void readFile(InputStream in, OutputStream out) throws IOException
  {
    byte[] buf = new byte[4096];
    int data;
    while ((data = in.read(buf, 0, buf.length)) != -1)
      out.write(buf, 0, data);
  }

I don't have issues with this logic and it is working fine.

Now I came across the post How To Read File In Java – BufferedReader in mykyong site and here the example uses BufferedReader .

Can someone please tell me which is the efficient way of reading a file in servlet code? when we need to prefer using BufferedReader in comparison to reading data in bytes.

There's almost no reason to read a file manually anymore since Java 7's NIO.

Just use Files.readAllBytes(Path) to read the full byte[] . Or if you want to stream directly to an OutputStream , Files.copy(Path, OutputStream) .

Can someone please tell me which is the efficient way of reading a file in servlet code? when we need to prefer using BufferedReader in comparison to reading data in bytes.

Any buffered method will work. Here, BufferedReader allows you to read streams as String values. As the javadoc says

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM