简体   繁体   中英

Reading and writing from text file in servlet

I want to write a string from my jsp page and store it in servlet. and if users enter the same string again servlet reads that string from the text file if it exist it tells the string is already been stored and if its not there it writes that string in text file.

Here is my code of jsp where i am getting string called "starting bid price"

       <%@page contentType="text/html" pageEncoding="UTF-8"%>
       <!DOCTYPE html>
       <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <h1>Hello World!</h1>
            <form action="mona.java" method="POST">
                Name:<input type="text" name="Name"><br>
                Email:<input type="text" name="Email"><br>
                Item Name:<input type="text" name="Item Name"><br>
                Item Description:<input type="text" name="Item Description"><br>
                Starting Bid Price:<input type="text" name="Starting bid Price"><br>
                <input type="submit" value="submit">
            </form>
        </body>
        </html>

Here is my code of servlet.

import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String s1 = request.getParameter("Name");
    String s2 = request.getParameter("Email");
    String s3 = request.getParameter("Item Name");
    String s4 = request.getParameter("Item Description");
    String s5 = request.getParameter("Starting bid Price");

    try{

        File file = new File("c:/example/filedata.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
                    String temp = bufferedReader.readLine();
        while (temp != null) {
        if(s5.equals(temp)) 
                    {
                    out.println("file already exist");
        //fileReader.close();
                    }
                    else 
                    {
                    PrintWriter fileWriter = new PrintWriter(new    
       FileOutputStream("c:/example/filedata.txt",true));  
                    fileWriter.println( s5 );
                    out.println("file saved");
                     fileWriter.close(); 
                            }
                    fileReader.close();
                    }
                     }  
    catch(FileNotFoundException fnfe) {    

  }  
  finally{  


      }  

}

Your question is a bit unclear, but if I understand well, you only need to make this piece of code work.

Well, first problem is

String temp = bufferedReader.readLine();
while (temp != null) {

Your code reads only first line from file, and if it is not null, you endlessly process the code in while loop.

Should be something like this:

String temp = null;
while ((temp = bufferedReader.readLine()) != null) {
   // do your stuff here.

Another possible problem:

out.println("file already exist");

If this should print text on console, it should be

System.out.println("file already exist");

Suggestions: While processing resources such as File, you should close streams/readers in finally block, because if exception occurs before resource is closed, resource remains opened.

And one opinion at the end. I personally wouldn't place File processing in servlet, it should be placed in some business logic class. Then I would call from servlet first method to test, if file contains specific string, and if not, I would call another method, which would append new line to existing file.

If you need something else not covered in my answer, please specify a bit more. Hope it helps.

Edit One more thing I noticed. When you find match in your file, you should terminate the while loop (return or break), or even better, define boolean variable as false before loop, if you find your match in file, set it to true and break loop. After while loop ends, test if variable is true, if not, append your line to file (not in while loop).

Edit2 Yes, it is the problem I mentioned above.

String temp = bufferedReader.readLine();
while (temp != null) {

If first line of file is not null, you'll process loop endlessly.

With modifying your code a little, I would suggest following:

 boolean found = false;
 File file = new File("c:/example/filedata.txt");
 FileReader fileReader = new FileReader(file);
 BufferedReader bufferedReader = new BufferedReader(fileReader);
 while ((temp = bufferedReader.readLine()) != null) {
   if(s5.equals(temp)) {
     System.out.println("file already exist");
     found = true;
     break;
   }
 }
 if (!found){
    PrintWriter fileWriter = new PrintWriter(new    
    FileOutputStream("c:/example/filedata.txt",true));  
    fileWriter.println( s5 );
    System.out.println("file saved");
 }

use

HttpSession session= request.getSession();
session.setAttribute ("name", name);

in order to save data in the session, and:

(String)session.getAttribute ("name");

to get it back

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM