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

Similar Messages

  • 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.

  • Interesting ? @ servlet reading a txt file

    hi friends,
    i need ur help for one interesting problem i m facing.
    I want to read a txt file and wanna display the text from that file into an html, using a servlet.A txt file contains sentences( words with spaces in between ).When servlet reads the file, it is reading the whole sentence ,but while displaying that sentence, it is just showing the first word of the sentence.
    html is not able to read the space between the words.
    so what do i suppose to do now.
    waiting for ur replies.......
    thanx
    amit

    hi friends ,
    i m giving the code , just give it a try//
    This is a servlet ---------------------------------------
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class AdminGraphServlet extends HttpServlet
    Properties ht;
    FileInputStream fin;
    FileOutputStream fout;
    String s15,st;
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,ServletException
    ht = new Properties();
    try
    fin = new FileInputStream("Data.txt");
    catch(FileNotFoundException e)
    System.out.println("FileNotFound");
    try
    if(fin != null)
    ht.load(fin);
    s15 = (String)ht.get("title");
    fin.close();
    catch(IOException e)
    System.out.println("Error Reading File");
    PrintWriter out = res.getWriter();
    res.setContentType("text/html");
    out.println("<html><body>");
    out.println("<form method=post action=http://localhost:8080/servlet/MyServlet>");
    out.println("<table><tr>");
    out.println("<tr><td>Title</td>");
    out.println("<td><Input Type=Text name=title value="+ s15 +"> </td></tr>");
    out.println("</table>");
    out.println("<input type=submit name=submit value=submit>");
    out.println("<input type=hidden name=check value=save>");
    out.println("</form>");
    out.println("</body></html>");
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    String Scheck = req.getParameter("check");
    PrintWriter out1 = res.getWriter();
    String ttl = req.getParameter("title");
    if(Scheck.equals("save"))
    ht.put("title",ttl);
    fout = new FileOutputStream("Data.txt");
    ht.store(fout,"Data");
    fout.close();
    out1.println("<html><body>");
    out1.println("<h1>Stored This Data Successfully</h1>");
    out1.println("</html></body>");
    txt file is having a line
    title=Are you smart enough?
    The servlet should display this sentence in a text box.
    But it is displaying only "Are".
    still waiting...
    have nice time..
    amit

  • 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();
        }

  • Use servlet read .csv file by ie, but why two more " ?

    Hi , friends
    following is the key method in my servlet used to read .csv file to ie , but , after I read file to client side , I found that in the both sides of every line " was added, so the csv file can have only one column (many columns was merged into one column), that was not what i want, who guys can find some idea? thanks for your enthusiasm!
    void serveRemoteFile(String sFileName, String sContentType, HttpServletRequest req, HttpServletResponse res, StringBuffer sbLog, Runtime rt){
    FileInputStream in = null;
    ServletOutputStream out = null;
    byte bBuf[] = null;
    int nLen;
    if (isBlank(sContentType) || isBlank(sFileName))
    return;
    res.setStatus(res.SC_OK);
    res.setContentType(sContentType);
    res.setHeader("Content-Disposition", "inline;filename= temp.csv");
    try {
    in = new FileInputStream(sFileName);
    out = res.getOutputStream();
    bBuf = new byte[1024];
    while ( (nLen = in.read(bBuf,0,1024)) != -1) {
    out.write(bBuf, 0, nLen);
    out.flush();
    out.close();
    }catch (FileNotFoundException e){
    errorPage(req,res,sbLog);
    }catch (IOException e){
    errorPage(req,res,sbLog);

    Excel uses a weird CSV file format. You can find more information about it and a Java library to read data from it here:
    http://ostermiller.org/utils/ExcelCSV.html

  • How to synchronize if one servlet read a file and anothe servlet update the

    How to synchronize if one servlet read a file and anothe servlet update the file at a time?

    Create a class that holds the reference to the file and do the whole file manipulation just in that class. than synchronize the read and write methodes. A reference to this file handler class can be stored to the servlet context in one servlet and read out from the servlet context in the other servlet.

  • 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();

  • JSF : Reading files greater than 200MB

    Hi,
    I am using JSF with tomahawk in my application.
    From the jsp i am calling a POJO to read a file (in a zip file) based on a condition. I am reading the whole file and returning back the full file...obviously i hit a java.lang.OutofMemory exception.
    I want to do something like send back each line (or chunk) that i read from the file back to the calling page.
    Here is the code that I have
    JSP:
    <pre>
    <%
         out.print(readObject.readFromZipFile(strPathToZipFile, logFileName);
    %>
    </pre>Here is the mehod readFromZipFile from the readObject class:
    public String readFromZipFile(String zipFilePath, String filePath) {
         StringBuffer sbFile = new StringBuffer();
         byte data[] = new byte[blockSize];
         BufferedInputStream is = null;
         try {
              ZipFile zipfile = new ZipFile(archivePath);               
              ZipEntry entry = (ZipEntry) zipfile.getEntry(filePath);                         
              is = new BufferedInputStream(zipfile.getInputStream(entry));
              while (bytesToRead > 0) {
                   data = null;
                   data = new byte[bytesToRead];          
                     sbFile.append(new String(data));
              is.close();
         } catch(Exception e) {
              log.error(e);
         } finally {
              is = null;
              data = null;
         return sbFile.toString();
    }I am reading the file and sending the data back as a string. Is there a way i can send the data back in chunks to the JSP / JSF and flush the data so that i dont hit the out of memory exception?
    Any help is highly appreciated.

    Hi BalusC,
    I tried this big time...i am getting roasted !!!
    This is what i tried in the servlet
    //get the size of the file
    int iFile = file.size();
    //start reading file from 5000 bytes
    int iPart = 5000;
    //read the file in part increments of 1000 bytes
    //so that we dont read the entire file at one shot
    while(iPart < iFile){
    //read the file from the given (start bytes)
    //to the (start bytes + 1000)
    response.getWriter().append
              (readZipFile(strPath,file,iPart,iPart+1000));
    //increment iPart to read the next 1000 bytes , next time around
    iPart = iPart + 1000;
    //flush the writer so that you can clear it
    response.getWriter().flush();
    }I still get a out of memory error...
    BTW i also tried response.getOutputStream().write()...
    This is apart from the read file method given above...what am i doing wrong here?

  • Generating the JSP from the Servlet source file

    Hi,
    Does anyone out there know if there is any utility/class/program which will generate a JSP from the Servlet Source file (.java file) or indeed from the compiled Servlet file (.class file)
    If its possible to decompile a .class file into a .java file, surely it must be possible to convert the .java souce file into the .jsp file that created it.
    any comments would be appreciated
    Richard

    I am the author of the original JSP!
    But I want to run a script on the generated Servlet source file,
    changing its contents, and then generate the JSP that would have created the new Servlet source file.
    but I need to know if theres anything that will reverse engineer a Servlet source into the generating JSP.
    its a kind of of Jeopardy type thing!

  • Applet read file on web

    Can applet read file on web?
    I try to write an applet that read the file on web i.e. http://lcoalhost:8080/test.txt
    The HTML page contain the applet is placed on http://localhost:8080
    URI URItemp= new URI("file:///test.txt");
    File Filetemp = new File(URItemp);
    BufferReader in = new BufferReader(new InputStreamReader(new FileInputStream(Filetemp)));the above cannot work
    Error : access denied (java.io.FilePermission \test.txt read)
    And then I add
    FilePermission fp = new java.io.FilePermission("file:///test.txt", "read");still cannot work
    Cound anyone tell me that is possible to do what I want to do?
    If yes, how?
    Thanks!!

    Applets are downloaded from web servers and execute on the client machine.
    Therefore they have no access to the web server file system, signed or not.
    They could have access to the client file system (the machine where they run),
    but for security reasons only signed applets have this privilege.
    So to answer your question, you sign if you want to access client files.
    To access web server files, you don't need to sign the applet, but you need
    to provide some method of accessing files remotely, for instance:
    - Files published for the web can be read using HTTP
    - Files can be read or writen with the help of an FTP server on the same machine as the web server
    - A servlet running on the HTTP server can collaborate with your applet to exchange files

  • How does a servlet read incoming XML??

    how does a servlet read incoming XML??
    thanks in advance
    annie
    Message was edited by:
    annie613

    Hi, anyone have an example code of sending a file to servlet and receiving the file in servlet?
    I have a JUNIT TEST wit the following code:
    ==========================================
                   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                   connection.setDoOutput(true);
                   connection.setDoInput(true);
                   connection.setAllowUserInteraction(false);
                   connection.setRequestMethod("POST");
                   out = new DataOutputStream(connection.getOutputStream());
                   BufferedReader reader = new BufferedReader(new FileReader(
                             "/Performance.zip"));
                   String line = null;
                   while ((line = reader.readLine()) != null) {
                        out.write((line + "\n").getBytes());
                   out.close();
                   // Read Response
                   InputStream in = connection.getInputStream();
                   int x;
                   while ((x = in.read()) != -1) {
                        System.out.write(x);
                   in.close();
                   BufferedReader r = new BufferedReader(new InputStreamReader(in));
                   StringBuffer buf = new StringBuffer();
                   while ((line = r.readLine()) != null) {
                        buf.append(line);
    =================================================
    and my SERVLET code is like following:
                   ServletInputStream in = request.getInputStream();
                   parameters = request.getParameterMap();
                   path += "file_" + request.getSession().getId() + ".zip";
                   // write the input stream to file
                   OutputStream fileOut = new FileOutputStream(path);
                   CRC32 crc = new CRC32();
                   long size = 0;
                   int read;
                   byte[] buf = new byte[8 * 1024];
                   while ((read = in.read(buf)) != -1) {
                        fileOut.write(buf, 0, read);
                        size += read;
                        crc.update(buf);
    Still when reading the InputStream, nothing is received in the servlet.
    Any idea how to fix it?
    thanks,
    Jari

  • Writing applets that read files hosted on a webserver.

    I have a java applet that I need to be able to read files on the webserver. IE open and render images. I know ultimately the user will end up downloading these images that are hosted on the websserver, but the java applet is set to read from it's local directory, for example, when I open up a text files, I use the path someFolder\someFile.txt. If the applet was placed in the same folder as someFolder on the webserver, how would I set it up to read from there opposed to on the machine executing the java code? Would I have to force the user to download all the resources, in thus case, wouldn't I need to to have the applet signed?

    ++++ to everything by malcolmmc (use class.getResource())
    Jeremy.W wrote:
    ...I could perform a CRC check and compare the archives with the ones on the server, but it still means I'd need to compress the archives manually every time an update is made to the files on the server.I am not sure whether you are concerned with the effort of doing this from your side. If so, use Ant to make your ..war file or whatever and just upload it (and restart the server?).
    If it is the archives (Jar or Zip) updating on the client that is your major concern, then I would definitely recommend the JNLP based option, which gives the client not only automatic update (the JWS client manages the time checks with the server), but if you want to go that far, direct programmatic access to the download API. I made a crude example (never properly finished) of downloading resources using the JNLP APIs DownloadService. (Though the standard 'auto-update' is known to be quite effective).
    Oh, and.. Of course, if you have a Java enabled server, the download servlet is known to be best for updates, incremental or otherwise.
    Does this applet really need to be embedded in a web page at all? JWS has offered these things to free-floating applets since Java 1.2, it is only recently an embedded applet could hook into the JNLP API.
    As to the 'Zip' archives of resources. Some points:
    1) It pays to split them up, especially if resources are likely to change frequently in one, but rarely for others. If you do that, webstart ensures the user only downloads the updated Jars. The only way to achieve a class/resource refresh in a conventional embedded applet ('plugin1') was to flush the class cache which would force refresh of all classes/resources.
    2) Splitting the archives according to type of resource can provide benefits in that the Jars can have different compression levels appropriate to the format.
    3) I would recommend deploying all resources, whether classes or other resources, in Jar and not Zip files. Sun has decided that no Zip will be checked to see if it is digitally signed, so Zip archives can cause problems for apps. which might need extended permissions (if it ever comes to that).

  • HOW TO DELETE ADOBE READER FILE FROM ADOBE READER

    HOW TO DELETE ADOBE READER FILE FROM ADOBE READER@ !@

    Your question make no sense. What exactly are you trying to do?

  • Reading Files from an FTP location based on Timestamp

    Hi,
    I have a requirement of reading files from an FTP location. The files should be read in the order they were saved in the folder. Can someone tell me how to solve this?
    Thanks,
    Ravi

    Hi Arik,
    Thanks for your reply. I tried doing what u said, but it isn't working. My requirement is to List the files in the folder using FTP adapter and get the file name with the least file stamp from the FTP adapter and pass the FileName dynamically to another FTP adapter which reads the file based on the FileName. When i tested after including the property (for listing the files) you mentioned, it is giving the following error (copied from flow trace):
    <messages>
    <input>
    <Invoke_getFileListFTP_FileListing_InputVariable>
    <part name="Empty" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <empty xmlns="http://xmlns.oracle.com/pcbpel/adapter/ftp/APP_SequentialFileTransfer/PRJ_SequentialFileTransfer/WS_GetFileList_FTP"/>
    </part>
    </Invoke_getFileListFTP_FileListing_InputVariable>
    </input>
    <fault>
    <bpelFault>
    <faultType>0</faultType>
    <bindingFault xmlns="http://schemas.oracle.com/bpel/extension">
    <part name="summary">
    <summary>Exception occured when binding was invoked. Exception occured
    during invocation of JCA binding: "JCA Binding execute of
    Reference operation 'FileListing' failed due to: Exception
    occured when binding was invoked. Exception occured during
    invocation of JCA binding: "Could not instantiate
    InteractionSpec
    oracle.tip.adapter.ftp.outbound.FTPListInteractionSpec due
    to: Cannot set JCA WSDL Property. Error while setting JCA
    WSDL Property. Property setListSorter is not defined for
    oracle.tip.adapter.ftp.outbound.FTPListInteractionSpec Please
    verify the spelling of the property. ". The invoked JCA
    adapter raised a resource exception. Please examine the above
    error message carefully to determine a resolution. ". The
    invoked JCA adapter raised a resource exception. Please
    examine the above error message carefully to determine a
    resolution.</summary>
    </part>
    <part name="detail">
    <detail>Cannot set JCA WSDL Property. Error while setting JCA WSDL
    Property. Property setListSorter is not defined for
    oracle.tip.adapter.ftp.outbound.FTPListInteractionSpec Please
    verify the spelling of the property.</detail>
    </part>
    <part name="code">
    <code>null</code>
    </part>
    </bindingFault>
    </bpelFault>
    </fault>
    <faultType>
    <message>0</message>
    </faultType>
    </messages>
    Thanks,
    Ravi
    Edited by: Ravi Santosh on Apr 24, 2012 11:02 PM

  • Reading file from an external folder.

    Iam tring to read an external file from the C:\ drive. Given below is the code.
    DATA LV_XLS(100) TYPE C.
    DATA LV_CONTENT TYPE XSTRING.
    LV_XLS = 'C:\XML\Report.xls'
    READ DATASET LV_XLS INTO LV_CONTENT.
    But when i execute iam getting an error - FILE NOT FOUND. How do i read file from an external folder. My requirement is to strictly read from an external folder. Please help.
    If this is not possible please advice as to how the file could be moved to the SAP root directory. Iam not able to locate the root.

    hi,
    This is the code to read a excel file from the local system.
    Read data set you are using in your code corresponds to files on application server thats the reason its throwing an error.
    * Parameter variable declaration for browsing the file location       *
    PARAMETERS:
      p_file TYPE ibipparms-path OBLIGATORY.
    data:
    it_text TYPE truxs_t_text_data .
    AT SELECTION-SCREEN  ON VALUE-REQUEST FOR p_file.
      CALL FUNCTION 'F4_FILENAME'
       EXPORTING
         program_name        = syst-cprog
    *   DYNPRO_NUMBER       = SYST-DYNNR
         field_name          = ' '
       IMPORTING
         file_name           = p_file.
    START-OF-SELECTION.
      CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP'
        EXPORTING
    *   I_FIELD_SEPERATOR          =
    *   I_LINE_HEADER              =
          i_tab_raw_data             = it_text
          i_filename                 = p_file
        TABLES
          i_tab_converted_data       = t_cust
      EXCEPTIONS
        conversion_failed          = 1
        OTHERS                     = 2
      IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    This is to read a text file from local system.
      CALL FUNCTION 'GUI_UPLOAD'
        EXPORTING
        filename                      =  'D:\FILEINTERFACE\file.TXT'
    *    FILETYPE                      = 'ASC'
         has_field_separator           = 'X'
    *    HEADER_LENGTH                 = 0
    *    READ_BY_LINE                  = 'X'
    *    DAT_MODE                      = ' '
    *    CODEPAGE                      = ' '
    *    IGNORE_CERR                   = ABAP_TRUE
    *    REPLACEMENT                   = '#'
    *  IMPORTING
    *    FILELENGTH                    =
    *    HEADER                        =
        TABLES
          data_tab                      = t_kna1
    *  EXCEPTIONS
    *    FILE_OPEN_ERROR               = 1
    *    FILE_READ_ERROR               = 2
    *    NO_BATCH                      = 3
    *    GUI_REFUSE_FILETRANSFER       = 4
    *    INVALID_TYPE                  = 5
    *    NO_AUTHORITY                  = 6
    *    UNKNOWN_ERROR                 = 7
    *    BAD_DATA_FORMAT               = 8
    *    HEADER_NOT_ALLOWED            = 9
    *    SEPARATOR_NOT_ALLOWED         = 10
    *    HEADER_TOO_LONG               = 11
    *    UNKNOWN_DP_ERROR              = 12
    *    ACCESS_DENIED                 = 13
    *    DP_OUT_OF_MEMORY              = 14
    *    DISK_FULL                     = 15
    *    DP_TIMEOUT                    = 16
    *    OTHERS                        = 17
      IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
    PS.  In both of the above mentioned function modules make sure that the file structure is similar to the internal tables used.
    Thanks
    Sharath

Maybe you are looking for

  • X205-s7483 Not burning

    Recently mi DVD-R unit stop recording file cd's, when i try tu burn a flie cd with alot of files the program burn it but the cd does not work, any computer can read it, but when i burn firs an image file, then i burn it in to the cd works grate. I wa

  • RE:run Solaris 8 on X86 laptop

    Hi Gurus, Anyone know which laptop can run Solaris 8 for Intel well? I just ordered Solaris 8 for Intel and am thinking to buy a laptop. i'd highly appleciate your help Gary

  • Installing CR VS2010 on Windows 2008 Core Server

    Hello, We are attempting to re-build our web servers and reduce their footprint. In this effort we have chosen to use Windows 2008 Core Server with all of the web server installation features. In addition we upgraded our application to CR for VS2010

  • SAP Lumira on terminalserver

    Hi, we use MS terminalserver and thin Clients. Are there any restrictions or settings for installation lumira on terminalserver. Regards Wolfgang

  • Using CDs and DVDs with the Lenovo X220

    Hi there, I apologize for the rudimentary question... I was recently given the X220 as a gift. It seems great--but I need to install programs, burn CDs, and watch DVDs on this thing! To do so, what do I need to buy? Can I get any old CD/DVD reader, o