Read file in servlet

In the servlet file, I create a new object which is class A(which is not subclass of servlet).
And class A have a method to read a txt file.
However, no matter I put the file in what directory such as tomcat/webapps/home/WEB-INF/classes, or just in home, when the servlet file and new the object of class A, and then call the read file method. java.lang.NullPointerException occurs.
How should I do?
thx~~

use the absolute path in the constructor
of the reader you use to read the file.
then it should work.

Similar Messages

  • Reading file in servlet

    Hi all,
    I have a servlet that processes an xml file containing information about books, creates ArrayList object from this information, and sends this data to jsp that display it. The problem is that somehow the data is read not from books.xml, but from books.txt. And the book.xml is ignored. Could anyone please help me to understand why it is so? Thank you very much.
    Here is the code for servlet:
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                   throws ServletException, IOException {
              ArrayList bookList = new ArrayList();
              String url = "/LibraryContents.jsp";
              synchronized(this) {
              HttpSession session = req.getSession(true);
              DOMParsing.parseBooks(bookList);
                 req.setAttribute("booklist", bookList);
                 ServletContext sc = getServletContext();
                 RequestDispatcher rd = sc.getRequestDispatcher(url);
                 rd.forward(req, resp);
    public class DOMParsing {
         public static void parseBooks(ArrayList bookList) {
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(false);
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   Document doc = builder.parse("C:\\books.xml");
                           getBookList(doc, bookList);
              }  catch (Exception e) {
                   e.printStackTrace();
    }     and the code for jsp:
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"
              xmlns:c="http://java.sun.com/jsp/jstl/core">
    <jsp:directive.page
      language="java"
      contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"
      session="true"/>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
    <title>Library</title>
    </head>
    <body>
    <h1>Books in the library</h1>
    <table border = "0">
    <tr>
    <td><b>Book title</b></td>
    <td><b>Author</b></td>
    <td><b>ISBN</b></td>
    <td><b>Pages</b></td>
    </tr>
    <c:forEach items="${booklist}" var="book">
    <tr>
    <td><c:out value="${book.name}" /></td>
    <td><c:out value="${book.author}" /></td>
    <td><c:out value="${book.ISBN}" /></td>
    <td><c:out value="${book.numberOfPages}" /></td>
    </tr>
    </c:forEach>
    </table>
    </body>
    </html>
    </jsp:root>

    Sure, put it in your WEB-INF directory. That should be in your servlet's classpath when it runs. UseInputStream is = this.getClass().getResourceAsStream("/config.xml");to read it.

  • Reading files from Servlets

    Hello
              Is it possible to configure WebApplication or server-based "default"
              directory for file i/o? I'd have need to read *.property-files that differ
              from one WebApplication to another (eg http://server/app1 needs different
              property-files than http://server/app2 - but they would be otherwise
              identical, same html, same servlets...).
              At the moment I have impression that no matter where servlet is located, if
              it opens a file, the "default" path is root-directory of WebLogic
              installation (/opt/weblogic for example) and all paths are relative to that.
              Thanks, Heikki
              Heikki Paatela, Designer, Yomi Vision Ltd
              P.O. Box 14, Kiviaidankatu 2 A, 00211 Helsinki, Finland
              Tel. +358 10 240 3827, GSM +358 50 337 1587
              Fax +358 10 240 3809, http://www.yomi.com
              

    Check out javax.servlet.ServletContext method getRealPath
    It returns the directory on your file system which is mapped to the root directory of your web context. In your case probably "c:/Tomcat/webapps/TestApp"
    Using that as a starting point, you can probably accomplish what you wish to.
    Good luck,
    evnafets

  • Read file from servlet

    I need to uplaod a file and convert that to bytearray. So that I can store in webserver or anywhere.
    Please suggest me . It's urgent

    go through this article
    http://www.onjava.com/pub/a/onjava/2001/04/05/upload.h
    tml?page=1 it gives you step by step instructions on
    uploading files. hope helps you!That's a great example. Can you give me some more examples

  • Read file with nio and flush with servlet

    Can I read file, by using java.nio (for example by FileInputStream.getChannel()) and then flush the file content thru the servlet?
    I kwow about reading without java.nio, get a byte array and then flush it by httpservletresponse writer or outputstream, but I wish to know if it is possibile with java.nio reading.
    thanks

    I'm doing it only for file reading..
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();    
            FileInputStream fis = null;                               
            try
                String path = "/var/hello.txt";
                fis = new FileInputStream(path);       
                FileChannel channel =  fis.getChannel();
                ByteBuffer bb = ByteBuffer.allocate((int) channel.size());
                channel.read(bb);
                byte[] data2 = bb.array();
                channel.close();
                out.write(new String(data2));
            } catch (FileNotFoundException ex)
                ex.printStackTrace();
            } finally
                try
                    fis.close();
                } catch (IOException ex)
    ex.printStackTrace();
                out.close();
        }

  • Servlet read file

    Hello everyone,
    I'm have written a web app in netbeans 6.8. Using JSP and Servlet. Tomcat6.
    My app reads xml file, do some things and writes another file. It is ok while I'm working throuth localhost. I just copy file's full path to jsp input type text, request the servlet to get parameter, it reads the file, writes another file, everything is ok.
    My question would be, is it possible to do same things on web server? When client enter the file path and app reads, writes it and so on...
    I tried to do that,
    at first I have the problem with permissions, I solved it by editing catalina.policy file, granted permissions in it. Now it is no errors, but the servlet gives me no results, It doesnt reads file ant so on.
    What could it be?
    Or the only way is:
    at first to upload file to server and then read it? But how could get my outputfile?
    Any help would be very appreciate.
    Edited by: peliukasss on Apr 15, 2010 4:54 PM

    peliukasss wrote:
    Hello everyone,
    My question would be, is it possible to do same things on web server? When client enter the file path and app reads, writes it and so on...
    I tried to do that,
    at first I have the problem with permissions, I solved it by editing catalina.policy file, granted permissions in it. Now it is no errors, but the servlet gives me no results, It doesnt reads file ant so on.
    What could it be?The server cannot reach the filesystem of the client of course. Would be terrible if web applications could do that, you go to a website, it reads your address book and then sends spam to all your friends on your behalf. Or it just starts deleting files at random. Terrible...
    >
    Or the only way is:
    at first to upload file to server and then read it? But how could get my outputfile?
    Any help would be very appreciate.
    Apache FileUpload combined with a multipart web form with a file upload component is what you need. Either that or give users the ability to upload files through an FTP client, and make the upload location available to your web application.
    Edited by: peliukasss on Apr 15, 2010 4:54 PM

  • How to read a file using servlet

    hi ,
    i've to read a file using servlet ,
    should read the file using servlet and display it in JSP,Could anybody get me how can i do it .
    Shiva

    To do that you need to get the response output stream and write yur file contents to that.
    response.setContentType(mimeType); //Set the mime type for the response
    ServletOutputStream sos = resp.getOutputStream();
    sos.write(bytes from your file input stream);
    sos.close();

  • Is it possible to create a file in servlet context? pls help me

    Is it possible to create a file in servlet context? pls help me

    Surely it is possible.File file = new File(path, name);

  • Uploading a file in Servlets

    I need help in uploading a file using servlets.help

    http://search.java.sun.com/search/java/index.jsp?col=ja
    aforums&qp=&qt=servlet+file+uploadThats a Master Link!!

  • HELP! File Upload Servlet and Internet Explorer

    Hello people. I hope this is an easy problem to solve...
    I have a servlet upload program that works using Mozilla browser (www.mozilla.org), but for some reason it doesn't work using Microsoft IE. The servlet is also using the servlet upload API from Apache (commons).
    I'm using IE version 6.0.2800.1106 in a Win98SE host computer. I get a cannot find path specified error message (see below). At work, I also get the same error message using IE, but don't know what version. The OS is XP. Unfortunately, at work, I can't install Mozilla browser (or any software-company policy) to see if Mozilla works there too. I would've like to have tested to see if the upload program worked on Mozilla on a truly remote computer.
    So I figured, it must be a IE configuration issue, but darn it!! I began by resetting IE to default settings, but still have the problem, I played around with several different combinations of settings in "Tools"-->"Internet Options...", and I still get the error message. Someone PLEASE HELP ME!!!
    Dunno, if it will help, I've also pasted the upload servlet source code below and the html file that's calling the upload servlet, but you still need the Apache commons file upload API.
    Trust me on this one folks, for some reason it works for Mozilla, but not for IE. With IE, I can at least access web server, and therefore, the html file that calls the upload servlet , so I don't think it's a Tomcat configuration issue (version 5.0). I actually got the code for the file upload servlet from a book relatively new in the market (printed in 2003), and it didn't mention any limitations as far as what browser to use or any browser configuration requirements. I have e-mailed the authors, but they probably get a ton of e-mails...
    Anyone suggestions?
    Meanwhile, I will try to install other free browsers and see if the file upload program works for them too.
    ERROR MESSAGE:
    "HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: C:\TOMCAT\webapps\MyWebApps\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
         com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:43)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    root cause
    java.io.FileNotFoundException: C:\TOMCAT\webapps\MyWebApp\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
         java.io.FileOutputStream.open(Native Method)
         java.io.FileOutputStream.(FileOutputStream.java:176)
         java.io.FileOutputStream.(FileOutputStream.java:131)
         org.apache.commons.fileupload.DefaultFileItem.write(DefaultFileItem.java:392)
         com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:36)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    note The full stack trace of the root cause is available in the Tomcat logs.
    Apache Tomcat 5.0.16"
    FILE UPLOAD SERVLET source code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.commons.fileupload.*;
    import java.util.*;
    public class FileUploadCommons extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.print("File upload success. <a href=\"/MyWebApp/files/");
    out.print("\">Click here to browse through all uploaded ");
    out.println("files.</a><br>");
    ServletContext sc = getServletContext();
    String path = sc.getRealPath("/files");
    org.apache.commons.fileupload.DiskFileUpload fu = new
    org.apache.commons.fileupload.DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setRepositoryPath(path);
    try {
    List l = fu.parseRequest(request);
    Iterator i = l.iterator();
    while (i.hasNext()) {
    FileItem fi = (FileItem)i.next();
    fi.write(new File(path, fi.getName()));
    catch (Exception e) {
    throw new ServletException(e);
    out.println("</html>");
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    doPost(request, response);
    HTML PAGE that calls the upload servlet:
    <html>
    <head>
    <title>Example HTML Form</title>
    </head>
    <body>
    <p>Select a file to upload or browse
    currently uploaded files.</p>
    <form action="http://##.##.##.####/MyWebApp/FileUploadCommons"
    method="post" enctype="multipart/form-data">
    File: <input type="file" name="file"><br>
    <input value="Upload File" type="submit">
    </form>
    </body>
    </html>
    Thanks in advance for any assistance.
    -Dan

    I'm guessing what is happening is that Mozilla tells the servlet "here comes the file myfile.zip". The servlet builds a file name for it:
        String path = sc.getRealPath("/files");
        // path is now C:\TOMCAT\webapps\MyWebApps\files\
        fi.write(new File(path, fi.getName()));
        // append myfile.zip to "path", making it C:\TOMCAT\webapps\MyWebApps\files\myfile.zipIE, however, tells "here comes the file C:\WINDOWS\Desktop\myfile.zip". Now imagine what the path+filename ends up being...
    So what you want to do is something along the lines of (assuming Windoze):
    public static String basename(String filename)
        int slash = filename.lastIndexOf("\\");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        // I think Windows doesn't like /'s either
        int slash = filename.lastIndexOf("/");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        // In case the name is C:foo.txt
        int slash = filename.lastIndexOf(":");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        return filename;
        fi.write(new File(path, basename(fi.getName()));
        ....You can make the file name check more bomb proof if security is an issue. Long file names trying to overflow something in the OS, NUL characters, Unicode, forbidden names in Windos (con, nul, ...), missing file name, ...

  • Problem in downloading file using servlet

    Hello,
    I wnat to send a file throung servlet to my desktop program. when i call this servlet through internet explore it is working fine but when i call this in my desktop program then desktop program get nothing. my desktop program does not get anything. please help me. here is my both code servlet and desktop program.
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
              response.setContentType("text/html");
         //     PrintWriter out = response.getWriter();
              File filename = new File("");
    //          Set the headers.
              response.setContentType("application/x-download");
              response.setHeader("Content-Disposition", "attachment; filename=" + filename);
    //          Send the file.
              OutputStream out = res.getOutputStream( );
              returnFile(filename, out); // Shown earlier in the chapter
              String filePath = getServletContext().getRealPath("/");
              response.setContentType("application/x-download");
              response.setHeader("Content-Disposition", "attachment; filename="+"amit.doc");
         //     File tosave = new File(getServletContext().getRealPath("), cfile.getName());" +
              try{
              File uFile= new File(filePath);
              int fSize=(int)uFile.length();
              FileInputStream fis = new FileInputStream(uFile);
              PrintWriter pw = response.getWriter();
              int c=-1;
    //          Loop to read and write bytes.
    //          pw.print("Test");
              while ((c = fis.read()) != -1){
              pw.print((char)c);
    //          Close output and input resources.
              fis.close();
              pw.flush();
              pw=null;
              }catch(Exception e){
    public class AdDesktopClient {
         * @param args
         public static void main(String[] args) {
              try{ 
              URL url = new URL("http://localhost:8080/WebRoot1/servlet/Download");
              //URLEncoder.encode(xmlString);
              URLConnection connection = url.openConnection();
              HttpURLConnection con = (HttpURLConnection)connection;
              con.setDoInput(true);
              con.setDoOutput(true);
              con.setUseCaches(true);
              con.setRequestMethod("GET");
              // PrintWriter out = new PrintWriter(con.getOutputStream());
              BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
              String inputLine;
              int len = con.getContentLength();
              InputStream inn = con.getInputStream();
              byte[] buf = new byte[128];
              int c =0;
              System.out.print("len :"+len);
              System.out.print(inn.read());
              while( (c = inn.read())!= -1){
                   System.out.print(c);
    /*          while ((inputLine = in.readLine()) != null)
              System.out.println(inputLine);
              in.close();
              }catch(Exception e){
                   e.printStackTrace();
    Plaease help me to solve this problem. i want to send a file throuhg a servlet to my desktop program.
    Thanks in advance
    Ravi

    Give this a try:
    File strFile = new File(strFileName);
    long length = strFile.length();
    response.setContentType("application/octet-stream");
    response.setContentLength((int)length);
    response.setHeader("Content-Disposition", ("attachment; filename=" + strFileName));
    OutputStream out = response.getOutputStream();
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(strFile));
    int i = -1;
    while((i = in.read()) != -1) out.write(i);
    in.close();
    Kris

  • Problem to include java script file in servlet

    I couldn’t use any functions included in java servlet file using servlet. I made a test in jsp and it work fine but in servlet not.
    Here my code
    out.println("<jsp:include page=\"C:/path/file.js\" flush=\"true\" />");
         or          
         out.println("<script language=\"javascript\" src=\"c:/path/file.js\">");
    Although was no error but using both didn’t let me use any function inside the java script file. As I said using the same command in JSP works fine.
    How I can include the file.js correctly ?

    [email protected] wrote:
    server machineOK, imagine that I am the server and you are the client.
    I have a file "c:/documents and settings/balusc/passwords.txt".
    So now you have the path. Can you tell me the contents of the file?

  • Getting tld file in servlet.

    hi all,
    now we cannot declare alias for tag lib tld in web.xml.so server will take tld from jar file which is there lib.
    i want access these tld file in servlet. can any body tell how to get it.
    thanks in advance...

    You could also use jsp, which provides you with JAVA functionality, however, omitting the printing. Here's an example:
    <%@ page contentType="text/html; charset=ISO-8859-5" %>
    <%
         String name = request.getParameter("name");
    %>
    <html>
    <header>
    </header>
    <body>
    <p><%=name %></p>
    </body>
    </html>

  • Display text file in servlet with preserved formatting(newlines, etc)

    how do i display a text file in servlet, but all the blanks and newlines are preserved.
    this is what i did:
    RandomAccessFile text = new RandomAccessFile("D:/FYP/tempMessage.txt","r");
    long length = text.length();
    byte[] bytes = new byte[(int)length];
    //Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
    && (numRead=deCiphered.read(bytes, offset, bytes.length-offset)) >= 0) {
    offset += numRead;
    // Close the input stream and return bytes
    text.close();
    String plainText=new String(bytes);
    //display in servlet
    pw.println("<center>Plain text: " + plainText + "</center>");
    the problem here is the newlines are seem to be omitted when they're displayed in a web browser, rendering the displayed text in a mess.
    any help are greatly appreciated. thanks in advance :)

    display text in between <pre></pre> tags.
    or display it inside a text area,dont worry abt the text area border, u can change that using style sheets.

  • How to read files on server from a java program?

    Hello,
    I am fairly new to JSP programming. I have an issue with reading files. I am trying to call method of a normal java file from a jsp program. The method I am trying to call does some IO operation on Files. I have the files in the same directory as my class files on server that is in WEB-INF/classes folder. In my java program, I am giving just the file name to open because the files and the classes are in the same directory. But this is not working.
    What exactly should I do to read a file from a java program, that is running on the server?
    Any help is appreciated.
    Thanks,
    Krishna

    String realFilePath = application.getRealPath("/WEB-INF/myFile.txt");
    File fileToOpen = new File(realFilePath);
    out.println(fileToOpen.getAbsolutePath() + ": exists? " + fileToOpen.exists());in this case "application" is a reference to the ServletContext.
    It is an implicit variable in a JSP. In a servlet:
    ServletContext application = getServletConfig().getServletContext();

Maybe you are looking for

  • Mini-DVI to S-Video Adapter doesn't work

    Hi, I am using the Mini-DVI to S-Video adapter from apple to connect my macbook to the TV. But the only thing I get is a grey flickering picture on my TV. When I click on the monitor-button I can see that my macbook detects only a monitor (but not a

  • Excel 2010 inplace not showing File tab

    Wondering if anyone else having an Excel 2010 inplace issue not showing the File ("Backstage") tab to allow Save or Save As operations?  Noticed others searched SAP xSearch help with similar Excel 2010 search terms but nothing relevant returned... We

  • No images in Google Play

    I have no images anywhere in Google Play Store.  When it was first pushed out I did.  Even at start up it's just a basic Apps, Music, Books, Movies, and Games Menu with no graphics.  If I go to staff picks, for example, it lists the picks but none of

  • Audio is disabled with my LED TV

    Hi, I have a new mac mini with lion version os, i'm using it as media center, and i'm connect it to my LG LED TV, every thing was working fine, even it correctly identifiy my TV and i can see it in the audio devices as "LG TV", but when lunch the PLE

  • How do I unlock keychain access?

    I keep getting popups requestiing keychain password. I tried to reset it to my log in password. Still doing the same thing. It is very annoying even though it disappears when I hit cancel. This just started in the past two weeks, and I have had my Ma