Solved

Servlet-how to read a file from servlet

Posted on 2000-05-08
9
444 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 7

Expert Comment

by:Ravindra76
Comment Utility

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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 1

Author Comment

by:haho
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
/**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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
topping2 challenge 13 56
HashMap Vs TreeMap 12 48
JDeveloper 12c for 32 bit 4 34
Java Timer (static) 9 9
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

743 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now