Solved

Servlet-how to read a file from servlet

Posted on 2000-05-08
9
455 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

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

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

738 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