This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes I/O and Streams and the fly likes Why does new File( Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Why does new File("MyFile.txt") in a web-app generate the file in context root?" Watch "Why does new File("MyFile.txt") in a web-app generate the file in context root?" New topic
Author

Why does new File("MyFile.txt") in a web-app generate the file in context root?

Mustafa Garhi
Ranch Hand

Joined: Nov 05, 2008
Posts: 111
I mean my first impression was it should be generated in the current directory.

So if My Context name is MyApp(a J2EE project ..)

and it has this structure (in addition to others):

MyApp/src/main/java/com/utils (src/main/java is in the classpath)

And i have a file creation util class say MyFileCreator.java in the utils folder having

File f = new File("MyFile.txt");

the above code creates the file in MyApp and not in the utils package ... WHY?
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41124
    
  45
Web apps do not have a concept of a "current directory", in particular not one tied to the currently executing class. It may be the root of the web app, but that's not specified, so you can't rely on it. That's why you need to use absolute paths in web apps.


Ping & DNS - my free Android networking tools app
Mustafa Garhi
Ranch Hand

Joined: Nov 05, 2008
Posts: 111
Hmm ..

Actually i realized that its eclipse that does that 'Create in context root' thing ..

You are right UD we cannot rely on that ..

Thanks bro
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19654
    
  18

For which ServletContext.getRealPath can help you out. For instance, to get a file in the root of the WEB-INF folder:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Mustafa Garhi
Ranch Hand

Joined: Nov 05, 2008
Posts: 111
Great

Thanks RP
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19654
    
  18

You're welcome.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why does new File("MyFile.txt") in a web-app generate the file in context root?
 
Similar Threads
Reading a text file from assets folders
Reading from a file
Basic build.xml file required
How to create File object for servlet and so where to place the folder
Cannot find file location