Subbu Subbu
Subbu Subbu

Reputation: 11

How to write into a text file inside web content folder from a servlet inside a project in java

FileWriter out = new Filewriter("/textfile.txt");

out.write("Hello");
out.close();

But unable to write into the file(file located inside the webcontent folder of my project)

Upvotes: 1

Views: 2794

Answers (2)

Java SE
Java SE

Reputation: 2073

Though Thilo's comments right. But if you really want to do then try this one.

//Suppose if it is on root webcontent folder
FileWriter out = new Filewriter("textfile.txt"); 
out.write("Hello");
out.close();

But if it is in some other folder within root webcontect folder then try this e.g. If file is in File folder then.

FileWriter out = new Filewriter("File/textfile.txt"); 
out.write("Hello");
out.close();

Upvotes: 0

Thilo
Thilo

Reputation: 262474

This is not a very good approach. Apart from relying on the fact that the web application is exploded by the container (as opposed to being served from the WAR file directly), it makes it tricky to deploy new versions of the app (you have to make sure not to clobber those generated files).

If you must do something like this, choose a different directory outside of the web application, set the path to that directory as configuration to your app and write the files there. You can then configure the web server to mount that directory into your URL space (so that it will look the same to browsers).

Upvotes: 3

Related Questions