Solved

Servlet-how to read a file from servlet

Posted on 2000-05-08
9
451 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
The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

 
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
V.simple question about Android packages and libraries 1 30
iterator/ListIterator approach 17 39
jboss wildfly 10.1 10 238
JAVA API design with micro service cloud in mind 1 47
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 …
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…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

830 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