Write to existing file using servlets

Every time I try to read an existing file using my current set of servlets, I get "File cannot be found". I don't understand what the problem is because I'm using the exact same location as the code where I read the document. Is there something else I'm missing? I've tried countless methods of writing, each will compile and such, but all give me the same result (IE nothing). Here's how my horrific code looks right now. Much was taken from the previous code that checks the passwords file.
Technically, it compiles and runs, but I get "java.io.FileNotFoundException: \WEB-INF\passwords (The system cannot find the path specified)" in the output. The file IS THERE and can be read in my password checking servlet without a problem...
package hw3Pack;
import java.io.*;
import java.util.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class passCheck extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
        response.setContentType("text/html");
        HttpSession session = request.getSession(true);
        PrintWriter out = response.getWriter();
        try {
                String filename = "/WEB-INF/passwords";
                String email = request.getParameter("email");
                String password = request.getParameter("password");
                String remember = request.getParameter("remember");
                ServletContext context = getServletContext();
          FileOutputStream fos = new FileOutputStream(filename);
                InputStream is = context.getResourceAsStream(filename);
          if (!is.equals(null)) {
               InputStreamReader isr = new InputStreamReader(is);
               BufferedReader reader = new BufferedReader(isr);
               String text = "";
                        } // if (is != null)
                else {
                } // else (password not blank)
        finally {
            out.close();
        } // finally
}

OK... I feel a bit dumb now... This code was working earlier (the writing part) and now it's not working since I added in the username check portion. It should be essentially complete at this point, I just need to figure out why it no longer writes the file. Any clues or insights?
I'm about to add a password checker (confirm both passwords entered on registration form are equal) Lets hope I don't mess more up...
package hw3Pack;
import java.io.*;
import java.util.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.net.*;
public class regComplete extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
        response.setContentType("text/html");
        HttpSession session = request.getSession(true);
        PrintWriter out = response.getWriter();
        boolean clear = true;
        try {
                String email = request.getParameter("email");
                String password = request.getParameter("password");
                out.println(email +" and " + password);
                String filename = "/WEB-INF/passwords";
                ServletContext context = getServletContext();
                InputStream is = context.getResourceAsStream(filename);
          if (!is.equals(null)) {
               InputStreamReader isr = new InputStreamReader(is);
               BufferedReader reader = new BufferedReader(isr);
               String text = "";
                        while ((text = reader.readLine()) != null) {              
                                StringTokenizer st = new StringTokenizer(text, "," );
                                String getEmail = st.nextToken();
                                String getPass = st.nextToken();
                                        if (email.equals(getEmail) && !email.equals(null)) {
                                                clear = false;
                                                out.println("I'm sorry but that email address is in use.  Please try again.");
                                        } else {
                                        //do nothing
                if (clear==true) {
                    File file = new File("/WEB-INF/passwords");
                    BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
                    out.println("going");
                    writer.append("\r\n" +email +"," +password);
                    out.println("Writing");
                    writer.close();
                    } else {
            } // try
        finally {
            out.close();
            } // finally
  }

Similar Messages

  • How to parse the xml file using servlet

    My scenario is like this:
    <b>FILE-->XI-->J2EE Application</b>
    XI sends the xml file to j2ee application. My servlet receives the file in HTTPRequest string. 
    How to parse that file using servlets.I should get the xml file as it is and should be displayed in the browser.
    Can anyone please help me with code, its urgent.
    Please help me!

    Download this java code
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/work/Echo02.java
    in your servlet code you can write
    public void doPost(req,resp){
    DefaultHandler handler = new Echo02();
    handler.parse(req.getInputStream());
    Offcourse you will need to modify the code of Echo02 class a bit to suit your requirement which would finally retrun you a string and you can then write it using
    respose.getWriter().write(responseString);

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

  • Write in a file using FileConnection

    Hello, I have to write in a file using the FileConnection API (JME).
    So far, I could write it, but I could not find out how to append in the file.
    Here is the code:
    FileConnection fc = (FileConnection)
    Connector.open("file:///test.txt");
    OutputStream os =  fc.Open(OutputStream);
    OutputStreamWriter osw = new OutputStreamWriter(os);
    osw.write("test");
    How can I add new data at the end of the file?

    Well, I really can't find a method I could use, so I read the file and put it in a buffer, then I write it all.
    I will let the code for anyone who needs:
    +try {+
    FileConnection fc = (FileConnection) Connector.open("file:///j9/test.txt");
    if (!fc.exists())
    fc.create();
    InputStream is = fc.openInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    +char[] c = new char[(int) fc.fileSize()];+
    isr.read(c);
    OutputStream os = fc.openOutputStream();
    String str = textField.getString() ',' + textField1.getString() + '\n';+
    os.write(new String(c).getBytes());
    os.write(str.getBytes());
    os.close();
    is.close();
    isr.close();
    fc.close();
    stringItem1.setText("It works");
    +}+
    +catch (Exception ex) {+
    stringItem1.setText("It doesn't work");
    +}+

  • How Do I write an XML file using Java?

    Hello there!! to everyone reading my post.
    I have this project I need to do, and I have no clue where to start, I was wondering if you guys could help me out.
    I need to know how to write an XML file using a Java Program, but without using a Third party library.... just using java native APIs.
    I will probably take the values to construct the file from a form.
    I will certainly appreciate if you could post some sample code for me.
    Thank you very much in advance..

    Hello there!,
    I have some doubts about the Tutorial I am currently reading. correct me If I'm wrong, but the section "Write a simple XML file" teaches you how to do so using a text editor. I need to create my XML file from a running Java Program written by myself, that takes the values to build it from some variables.
    If I'm totally wrong about what I'm saying, could you please point me to where I can find the information of how to do what I'm asking for, inside the tutorial.
    Thank you very much,...
    sincerely.

  • Download a file using servlet

    Hi,
    i need to download a file using servlet (jsp frontend) and if the download is successful, then a success message shud be displayed on the jsp.
    i have tried it using MultipartResonse object and have been able to download the file. The problem is displaying the message on a jsp after download. After download if i use RequestDispatcher object to forward control to another jsp, it doesnt happen.
    Can anyone help me with this?

    Hi,
    You can check :-
    http://www.servletsuite.com/servlets/download.htm
    Best of luck.
    R S

  • How to write data to existing file using spool command?

    Hi,
    I am calling a stored procedure from a shell script. This stored procedure is having a CLOB object as an OUT parameter. How to write the data in CLOB object a existing file which is there in my client system. Below is the shell and sql scripts.
    Shell script
    ( echo "hello" ) > /root/file.txt
    sqlplus -s $user/$pass@$tns @/root/proc.sql /root/file.txt << EOF
    EOFSQL script
    set pages 0
    set trimspool off
    set serveroutput off
    set feedback off
    set term off
    set echo off
    variable out CLOB
    define file='&1'
    begin
    pack.proc(:out);
    end;
    spool &file
    select :out from dual;
    spool offThis code writes contents of the OUT variable to file.txt, but my existing data ('hello') is lost. Please help me.
    I figured the it...Use append in the spool command... :)
    Edited by: Balaji on Jul 19, 2012 8:55 PM

    >
    Hi Balaji
    I figured the it...Use append in the spool command... :Please mark the thread as answered as per the FAQ.
    Paul...

  • Write to a file using a system variable in the path

    I got an error when I used the following command to write a file
    OdiOutFile "-FILE=<%=System.getProperty("LOG")%>\test.log" -APPEND "-CHARSET_ENCODING=ISO8859_1" "-XROW_SEP=0D0A"
    The "LOG' is an environment variable.
    The error is
    java.lang.Exception: Oracle Data Integrator Function does not exist
    It looks like ODI treat System.getProperty as ODI function instead of java method. I use SUNOPSIS API as technology in the command

    At this moment I can't give a source code example because I'm writing it :) and I'm trying to see the cases where I may have some problems.
    But my idea is to access the file at any time and to write into it with differenent threads in a differenet places in this file. In fact the problem I'm trying to solve is :
    I have a objects called Data that are generated by some other thread independent of my application. This thread puts the Data objects in some kind if buffer. When the buffer is full, I'm creating a few threads fo every object Data in this buffer (the data objects in its own is some collection of floats and doubles) So I'm trying to position the new created threads over the file but in different places and then make them write the data collected in the object Data.
    To position de threads over the file, I'm accessing it by some synchronous method to undestand where it can write in this file and the writing is not synchronous because I'm trying to calculate the exact place and number of bytes of writing and in this way to avoid (may be) the eventuality of errors.
    Regards,
    Anton

  • Write into existing file with "write to text file"

    Hi all,
     I have a text file that contains several lines of data (text). Now I would like to replace the first three lines with text coming from a string array.
    My approach is shown in WriteToFile.vi that is attached.
    When I am executing this vi (with an empty file), everything seems to be working fine in the first place.
    The file will contain the following text:
    oneoneone
    twotwotwo
    threethreethree
    Now, when the third element in the array is shortened (lets say to "threethr") before execution,  the file will contain  the following text:
    (the file was not emptied before execution)
    oneoneone
    twotwotwo
    threethr
    three
    How can I avoid the last line being written? I have made many tests and I could not find a solution.
    One more example:
    Lets say we have an existing file, inside this file is:
    oneoneone
    twotwotwo
    three
    fourfourfour
    Now I would like to overwrite line three with "threethreethree". Therefore I execute my vi as shown in the attachment.
    What I get as a result is:
    oneoneone
    twotwotwo
    threethreethree
    ur
    So, the text in line four, which should not be touched, is "ur" instead of "fourfourfour".
    Any idea to solve this problem?
    What I basically need is replacing a line of a text file in a conveinient way.
    Thanks,
    Holger
    LV 8.5.1
    Attachments:
    WriteToFile1.jpg ‏17 KB
    WriteToFile.vi ‏11 KB

    The remaining fourth line is there because the third line has a <nl> at the end. You have not emptied the file so the rest of the file will be kept. This is because your line is shorter.
    In the scond example the third line is longer and it will overwrite the beginning of the fourth line.
    Files aren't organized in lines they are oganized in bytes. And what you write are bytes to the file even with text files.
    Replacing a single line in a file is done by reading the file line by line. All unchanged lines are written to a temporary file and the line with the new text will be written instead of the original line to the temporary file. When the writting is done rename the original file, then rename the new file into the original file and then delete the renamed original file.
    Waldemar
    Using 7.1.1, 8.5.1, 8.6.1, 2009 on XP and RT
    Don't forget to give Kudos to good answers and/or questions

  • Read and write into csv file using procedure

    I would like to read a particular column value from csv file(which will have many columns) using procedure and for that value I have to retrieve some more values from database table and have to append into same csv file.
    can someone help me?
    Thanks
    Edited by: 1002478 on Apr 25, 2013 5:52 AM
    Edited by: 1002478 on Apr 25, 2013 5:55 AM

    1002478 wrote:
    thanks for your reply.
    Using UTL_FILE i'm able to read csv file. I'm stuck up in appending some more columns to same csvYou'll struggle to append data to an existing CSV.
    You'd be better to read the data from one CSV, and create another CSV using that data, and the extra data you want, and then when finished, delete the original file and rename the new file to the old filename.
    You should be able to do that using External Tables to read the source file (easier than using UTL_FILE) and UTL_FILE to write the new file.

  • How to download a file using servlet

    I have a problem about downloading a file using a servlet.
    Anybody can help me?
    Thanks

    I am assuming that you want to write a servlet that, when invoked by a user (for instance, through a URL link), will download a file using the "save as" dialog (on Windows, for example) in the user's browser.
    In such a case, all you need to do is get the OutputStream from the response object, set the proper MIME type header, and write the file. Here is an (untested, not even compiled) skeleton.
    public class MyServlet extends HttpServlet {
    protected void doGet (HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    ServletOutputStream out = resp.getOutputStream ();
    resp.setContentType ("application/x-foobar");
    while (/* whatever */) {
    In this loop, you generate your "file's" data.
    You can compute it on the fly, pull it from a database,
    read it from a "real" file, or any other means you can dream up.
    The sample line below just writes some of the data (for example,
    a byte array) to the user's browser via the output stream out.
    out.write (data);
    out.flush ();
    Go to http://java.sun.com/j2ee/sdk_1.3/techdocs/api/index.html
    for the JavaDoc on the classes used.
    Cheers!
    Jerry Oberle

  • How to write to log files using java files from JSP

    Anybody knows different options in writing to log files using JSP?

    Do you have an example?in the init() method of the servlet put the following
            FileOutputStream out = new FileOutputStream("your-log-file");
            PrintStream ps = new PrintStream(out);
            System.setOut(ps);
            System.setErr(ps);load the servlet on startup using <load-on-startup> in web.xml

  • 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

  • How to write as XML file using java 1.5

    hi all,
    i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
    can any body help me out to solve this issue.......
    thankx in advance
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.DocumentHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.ParserFactory;
    import java.io.*;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                   
                   dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();                   
    Document xmlDoc =  db.newDocument();
    // this creates the xml document ref
    // parent node reference
    Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
    // root node
    xmlDoc.appendChild(rootnd);
    Element rownd = (Element) xmlDoc.createElement("ROW");
    rootnd.appendChild(rownd);
    Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
    rownd.appendChild(statusnd);
    statusnd.appendChild(xmlDoc.createTextNode("Y")
    FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
    Writer outf = new OutputStreamWriter(outpt, "UTF-8");
    //error is occuring here Since write method is not available in the Document class
    xmlDoc.write(outf);
    outf.flush();

    Hi,
    when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
    However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this:     TransformerFactory tf = TransformerFactory.newInstance();
         // set all necessary features for your transformer -> see OutputKeys
         Transformer t = tf.newTransformer();
         t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
    Hope it helps.

  • Write to a file using several threads

    Hello,
    I'm trying to implement a writing procedure into a file using several different threads. The idea I have is to make each thread to write in a different place in the file. In your opinion is there a possibility of some incoherence.
    Regards,
    Anton
    Edited by: anton_tonev on Oct 22, 2007 3:28 AM

    At this moment I can't give a source code example because I'm writing it :) and I'm trying to see the cases where I may have some problems.
    But my idea is to access the file at any time and to write into it with differenent threads in a differenet places in this file. In fact the problem I'm trying to solve is :
    I have a objects called Data that are generated by some other thread independent of my application. This thread puts the Data objects in some kind if buffer. When the buffer is full, I'm creating a few threads fo every object Data in this buffer (the data objects in its own is some collection of floats and doubles) So I'm trying to position the new created threads over the file but in different places and then make them write the data collected in the object Data.
    To position de threads over the file, I'm accessing it by some synchronous method to undestand where it can write in this file and the writing is not synchronous because I'm trying to calculate the exact place and number of bytes of writing and in this way to avoid (may be) the eventuality of errors.
    Regards,
    Anton

Maybe you are looking for

  • Error while calling a webservice on ECC 5.0 box

    Hi    I have a webservice exposed on a ECC5.0 - the webservice is available for runtime. But when I call it with a single input parameter - from a test SOAP test - I get the following error as the SOAP response What could this be/mean ? Please help.

  • Requisitioner Help in Purchase Order Create  / Change / Display

    Hi Friends, Requiremnet : i want F4 Help in the Requisitioner Field from the Employee Master Table Is there any Exit or Enhancement Spot for this. Regards: Sridhar.J

  • Unable to call c++ .so file in java

    this is my java file prog1.java class prog1      static           try                System.loadLibrary("test");           catch(UnsatisfiedLinkError ule)                System.out.println(ule);                //ule.printStackTrace();      public sta

  • Do I have enough "horsepower" to adequately run Leopard?

    Hello there, This are my specs: Dual 1GHz MDD, 2 GB RAM, ATI RAdeon 9800 Pro (128), Maxtor 500 GB (16 MB cache) for system and apps, Maxtor 500 GB (16 MB cache) for documents. Both drives are connected to the ATA100 on-board controller. Is this enoug

  • "B2B adapter general error"

    I had an inbound EDI document fail with a"B2B adapter general error". I have never seen anything like this error -- and there are no details in the b2b log. This type of doc processes inbound to B2B hundreds of times daily, and the EDI looked valid.