Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Servlet-how to read a file from servlet

Posted on 2000-05-08
9
Medium Priority
?
466 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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 200 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

Independent Software Vendors: 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!

Question has a verified solution.

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

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…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

610 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