Solved

Servlet-how to read a file from servlet

Posted on 2000-05-08
9
448 Views
Last Modified: 2013-11-24
The following code is in a servlet file named "Display.java" (it is called from the doGet() method).  The file that I want to read in from Display.java named "test.html".  Both of them are in the same directory.  But I always got an IOException.  Is this a correct way to read in a file from servlet? if not, can you post a piece of code that works or just a suggestion!

thanks in advance,

RandomAccessFile raf = null;
try
{
   //try to read in a file to parse
   raf = new RandomAccessFile("test.html", "r");  

   //for (;;)...
}
catch(IOException io)
{
  //I have IOException here
}
0
Comment
Question by:haho
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 7

Expert Comment

by:Ravindra76
ID: 2791279
public StringBuffer readFile(String filename) throws IOException{
            
            StringBuffer tmpbuf = new StringBuffer();
            
            FileReader fd = new FileReader(filename);
            BufferedReader in = new BufferedReader(fd);
            String tmp;
            
            while((tmp = in.readLine())!=null){
                  tmpbuf.append(tmp).append("\r\n");
            }
            fd.close();
            Logger.sendData(1090,"file read as "+filename);        
            return tmpbuf;
}
0
 
LVL 1

Expert Comment

by:yanchou
ID: 2791346
Hi, haho

Servlet class directory, public html directory, file directory are three different directories. The file directory (where you should put the "test.html")is  depended on the platform and web server. For example, Apache JSERV(Win NT)web server's file directory should be "htdocs/..", (Most NT version's file directory is in the parent directory of public html folder)
While Apache JSERV's file directory should be the "root")

You can do a simple testing with the following code


File file = new File("whatever");
log(file.getAbsolutePath());

0
 
LVL 1

Author Comment

by:haho
ID: 2792988
ravindra76,

This method only works if you are not running from the servlet.

I have tried this.  The exception is:
"java.io.FileNotFoundException".
thanks anyway.
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 7

Expert Comment

by:Ravindra76
ID: 2793024

There is no difference between file reading from servlet and other applications

Try with this example.

Assume that You have sample.html in c drive.

Then U have to give file name as

String filename = "c:\\sample.html";

Next time give the exception stack trace.

java.io.filenotfound means U are giving wrong path.

Check this once.

0
 
LVL 1

Author Comment

by:haho
ID: 2793643
I am not running from Window.  I access my servlet from a browser with a URL and my servlet is stored in a Linux system.  The browser loads the servlet but can't find the file that I want to read.  RandomAccessFile is what I've been using for years and it works fine.

I just asked the Admin.  and they said that I have to store the files that I want to read in a difference directory.  It should be under "htdocs".  Earlier, yanchou pointed out this but I don't have write permission to this directory that's why I leave the question open so that someone can give me an alternative way to read the file-perhaps base on the URL object.

thanks
0
 
LVL 1

Expert Comment

by:yanchou
ID: 2793709
haho

It is unlikely to be in htdocs directory but very likely in the parent directory of htdocs.

BTW, If you are using jswdk or Apache jserv, the directory is configurable
0
 
LVL 1

Accepted Solution

by:
yanchou earned 50 total points
ID: 2794050
Haho

It is unlikely to be be under "htdocs", possibly be the parent directory of "htdocs".

BTW, Most servlet engine allow you to configure the location of file, like Jserv and JSWDK.


0
 

Expert Comment

by:anilbathula
ID: 2816270
/**testServlet.java**/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class Display extends HttpServlet {
   
    RandomAccessFile raf = null;

    //Initialize global variables
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    }
       
 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException {
        try
        {
            //try to read in a file to parse
            raf = new RandomAccessFile("c:\\jsdk2.1\\webexample\\web-inf\\servlets\\testServlet.java", "r");
            String str = null;
            while ((str = raf.readLine()) != null) {
                System.out.println(str);
            }
        }
        catch(IOException io)
        {
            //I have IOException here
            System.out.println("Error:" + io);
        }
    }
}

I tested this example, this program reading the particular file and printing on server side.
0
 
LVL 1

Author Comment

by:haho
ID: 2817462
You point out the right way to find an answer.  I don't have write permission directly to the htdocs.  But in looking into this, I found out that I have a r/w permission to 1 of the htdocs' sibling directory.  So it works when I store my files there.

thanks.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question