LearnFast.Ninja

Java servlet load file resource text

In this tutorial we show you how to use java to read file to string. Tell java to read the file by bytes and set the java charset to utf-8.

Step 1: Create static file with some content inside.


Step 2: Open your servlet then in the doGet function write this code.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       PrintWriter oPrintWriter = response.getWriter();

       String Html = getFileToString(getServletContext(), "Static.html");

       oPrintWriter.print(Html);

}


Step 3: This is the implementation of the function that get ServletContext and file path.

public String getFileToString(ServletContext servletContext, String filePath) throws IOException {

       String path = servletContext.getRealPath(filePath);

       String Content = "";

       FileInputStream stream = new FileInputStream(new File(path));

       try {

              FileChannel oFileChannel = stream.getChannel();

              MappedByteBuffer oMappedByteBuffer = oFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, oFileChannel.size());

              Content = Charset.forName("UTF-8").decode(oMappedByteBuffer).toString();

       }

       finally {

              stream.close();

       }

       return Content;

}


Result:


Tags

java

servlet file bytes buffer