rose petal
rose petal

Reputation: 21

JSP write to a text file

I am creating HTML input form with submit button. The form action takes us to a jsp page. I wrote this on my JSP page

        ServletContext context = this.getServletContext();

        String path = context.getRealPath("WEB-INF/list.txt");


        User user = new User(fName, lName, eAddress, phone, company, webinar,dateObj);
        UserIO.add(user, path);

Then I created a java class called UserIO

public class UserIO {

    public static void add(User user, String path) throws IOException  
     {
        FileOutputStream fos= new FileOutputStream(path, true);

        PrintWriter out = new PrintWriter(fos);//, true));

        out.println(user.getFname() + "|" + user.getLname() + "|" + user.getEmail() + "|"   );
         out.println(user.getPhone() + "|" + user.getCompany() + "|" + user.getWebinar() + "|" + user.getDate());

        out.close();
    }

}

Now my problem is, The output shows on the JSP page but does not save to text file.

I have done this program in Netbeans and saved the file under <projectname>/web/WEB-INF.

I tried changing the path to <projectname>/web/WEB-INF/list.txt but gav me error msg. So stuck changed it as above.

Tell me your expert opion how to fix this?

Upvotes: 2

Views: 9215

Answers (3)

Shaon Hasan
Shaon Hasan

Reputation: 740

look for the txt file inside your projects 'build\web\WEB-INF\' directory(). I faced the same problem , then i found the text file in the given directory. :-) By the way, what i am saying is if you are using Netbeans IDE..

Upvotes: 1

Matin Kh
Matin Kh

Reputation: 5178

I think, I found your answer:
Try using this:

(I assume that the file is found)
To write in your file, you should replace your code with these:

FileOutputStream fos= new FileOutputStream(path, true);
fos.write((user.getFname() + "|" + user.getLname() + "|" + user.getEmail() + "|").getBytes());
fors.write((user.getPhone() + "|" + user.getCompany() + "|" + user.getWebinar() + "|" + user.getDate()).getBytes());


And done!

Upvotes: 0

Matin Kh
Matin Kh

Reputation: 5178

You have to provide FileOutputStream the correct path!
Is there any folder, named WEB-INF in your eclipse directory. I think not!
Try using these lines to understand where the file is being created:

File file = new File("list.txt");
System.out.println(file.getCanonicalFile());


Upvotes: 0

Related Questions