Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating file in the web server  RSS feed

 
Zoram Paul
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello experts!

Actually while executing:
String s =config.getServletContext().getRealPath("/");

I got the string as: /home/cascanicacom/public_html/

Thats the root I suppose.

But after getting the root path. Now I need to create a file "write.txt" and save it in the /home/cascanicacom/public_html/ folder.

The code i used before was :
File file = new File("write.txt");

Now please tell me where should I make the changes in the
File file = new File("write.txt"); so as to create it in the server(under /home/cascanicacom/public_html/ folder.).

I even tried:
File file = new File("/home/cascanicacom/public_html/write.txt");

And when I checked in the server theres no file there.

HELP

Thank you so much for all your help.
 
Bosun Bello
Ranch Hand
Posts: 1512
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you have just declares the file. It does not create it.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A quick warning about relying on getRealPath then I'll move this to our IO forum because it sounds like you've got all the servlet specific aspects solved.

Depending on how your application is deployed, getRealPath may or may not work. If your app was deployed from an exploded file system or if your container unzips the war file into directory on deployement, then getRealPath will work fine. If, on the other hand, you deploy your app from a war file or ear file and the container doesn't unpack it, then getRealPath will return null because, there really isn't a path to return.
It's important to keep this in mind because it limits your deployment options and the apps overall portability down the road.

Moving to IO where you will get better help with files.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bosun Bello:
What you have just declares the file. It does not create it.


True, to create the file, you need to call createNewFile() method of File. This will work if and only if the directory exists. If it does not then use mkdirs() method first on the root directory File instance.

The following code will help:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!